链接:Problem - 1167C - Codeforces
思路:本题是一道并查集的应用题,主要添加一个size数组记录组的长度。关键的关键,注意N开5e5(本人没注意开了个2e5,交了还总是TLE,查了半天 T_T)
code:
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,t,k,l,r,q,x,idx,res,cnt,sum,flag,maxx,minn;
const int N=500010;
const int MOD=1e9+7;
const int INF=0x3f3f3f3f3f3f3f3f;
int p[N],s[N];
int find(int x) {
if(p[x]!=x)p[x]=find(p[x]);
return p[x];
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=1; i<=n; i++) {
p[i]=i;
s[i]=1;
}
while(m--) {
int o;
cin>>o;
if(o>1) {
o--;
int tem;
cin>>tem;
while(o--) {
int l;
cin>>l;
if(find(tem)==find(l))continue;
else {
s[find(tem)]+=s[find(l)];
p[find(l)]=find(tem);
}
}
} else if(o==1)cin>>k;
}
for(int i=1; i<=n; i++) {
cout<<s[find(i)]<<" \n"[i==n];
}
return 0;
}