← Home
#include<bits/stdc++.h>
using namespace std;
vector<int> a[200005];
int f[200005], dp[200005], cd[200005];
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int t; cin>>t;
    for(int test = 0; test < t; test++){
        int n, m; cin>>n>>m; dp[0] = cd[0] = 1;
        for(int i = 1; i <= n; i++){
            int x; cin>>x; a[i].clear();
            for(int j = 1; j <= x; j++){
                int y; cin>>y; a[i].push_back(y);
            }
        }
        //Calculate dp
        int j = 1, duplicate = 0, lastzero = 0;
        for(int i = 1; i <= n; i++){
            dp[i] = 0;
            if(a[i].size() == 0) lastzero = i;
            for(int x : a[i]) if(f[x]++ == 1) duplicate++;
            int lastj = j;
            while(duplicate > 0){
                for(int x : a[j]) if(--f[x] == 1) duplicate--;
                j++;
            }
            //First, we could erase the segment without using the empty subset
            if(j >= 2){
                dp[i] = cd[j-2];
                if(lastj >= 2) dp[i] -= cd[lastj-2];
            }
            //Else, we could erase the segment
            if(lastzero >= lastj){
                dp[i] += cd[lastzero-1];
                if(lastj >= 2) dp[i] -= cd[lastj-2];
            }
            dp[i] = (dp[i] > 0); cd[i] = cd[i-1] + dp[i];
            //cerr<<"A"<<i<<" "<<j<<" "<<dp[i]<<endl;
        }
        //Then we calculate the answer
        for(int i = 1; i <= n; i++) for(int x : a[i]) f[x] = 0;
        int ans = 0, sum = 0; duplicate = 0;
        for(int i = n; i >= 1; i--){
            for(int x : a[i]) if(f[x]++ == 1) duplicate++;
            if(duplicate > 0) break;
            if(a[i].size() == 0) sum = m;
            else sum = min(sum + (int)a[i].size(), m);
            if(dp[i-1] == 1) ans = max(ans, sum);
        }
        for(int i = 1; i <= n; i++) for(int x : a[i]) f[x] = 0;
        cout<<ans<<'\n';
    }
}