1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
| #include<bits/stdc++.h> #define int long long #ifdef DEBUG #define debug(...) fprintf(stderr,__VA_ARGS__) #else #define debug #endif using namespace std; bool Begin; const int max_n=200005; int read(){ int x=0;bool w=0;char c=getchar(); while(!isdigit(c)) w|=c=='-',c=getchar(); while(isdigit(c)) x=x*10+(c^48),c=getchar(); return w?-x:x; }
int n,m; vector<int> a;
int tot; map<int,int> mp;
int ps[max_n]; int ID(int x){ if(mp[x]) return mp[x]; ++tot; mp[x]=tot; ps[tot]=x; return tot; }
struct graph{ int nx[max_n],ct,hd[max_n],to[max_n],deg[max_n]; graph(){ct=0;} void clear(int n){ for(int i=1;i<=n;++i) hd[i]=0,deg[i]=0; ct=0; } void add(int v,int u){ ++deg[v]; nx[++ct]=hd[u],hd[u]=ct,to[ct]=v; } }e; vector<int> L; priority_queue<int> R;
int ed[max_n]; void dfs(int u,int num){ ed[u]=num; for(int i=e.hd[u];i;i=e.nx[i]){ int v=e.to[i]; if(!ed[v]) dfs(v,num); } }
bool End; #define File "" signed main(void){ #ifndef ONLINE_JUDGE freopen(File ".in","r",stdin), freopen(File ".out","w",stdout); #endif debug("Memory: %lf MB\n",(&Begin-&End)/1024.0/1024); for(int T=read();T;--T){ n=read(),m=read(); e.clear(tot); L.clear(); for(int i=1;i<=tot;++i) ps[i]=0,ed[i]=0; mp.clear();tot=0; while(!R.empty()) R.pop(); for(int i=0,_n;i<n;++i){ _n=read(); a.clear(); a.emplace_back(-1); for(int j=0;j<_n;++j) a.emplace_back(read()); sort(a.begin(),a.end()); a.erase(unique(a.begin(),a.end()),a.end()); a.emplace_back(1145141919810LL); _n=a.size(); int l=-1,r=-1; for(int j=1;j<_n;++j) if(a[j]!=a[j-1]+1){ if(l==-1){ l=a[j-1]+1; if(a[j]!=a[j-1]+2){ r=l+1; break; } } else{ r=a[j-1]+1; break; } } L.emplace_back(l); e.add(ID(l),ID(r)); R.push(r); } sort(L.begin(),L.end()); L.erase(unique(L.begin(),L.end()),L.end()); while(!R.empty()){ int st=mp[R.top()];R.pop(); if(!ed[st]) dfs(st,ps[st]); } int res=0,mx=-1; int _n=L.size(); for(int i=0;i<_n;++i) mx=max(mx,L[i]); for(int i=1;i<=tot;++i) if(e.deg[i]>=2) mx=max(mx,ed[i]); int cnt=0; if(mx>m){ for(int i=0;i<_n;++i) if(L[i]<=m){ res+=max(mx,ed[mp[L[i]]]); ++cnt; } res+=(m+1-cnt)*mx; } else{ for(int i=0;i<_n;++i) if(L[i]<=mx){ res+=max(mx,ed[mp[L[i]]]); ++cnt; } res+=(mx+1-cnt)*mx; res+=(mx+1+m)*(m-(mx+1)+1)/2; for(int i=0;i<_n;++i) if(L[i]>mx && L[i]<=m) if(ed[mp[L[i]]]>L[i]) res=res-L[i]+ed[mp[L[i]]]; } printf("%lld\n",res); } return 0; }
|