并查集
The Suspects http://poj.org/problem?id=1611
1 #include<cstdio> 2 #include<cstring> 3 #define mt(a,b) memset(a,b,sizeof(a)) 4 const int M=30010; 5 class UnionFindSet { //并查集 6 int par[M],num[M]; 7 public: 8 int getnum(int id){ 9 return num[getroot(id)]; 10 } 11 void init() { 12 mt(par,-1); 13 for(int i=0;i<M;i++) num[i]=1; 14 } 15 int getroot(int x) { 16 int i=x,j=x,temp; 17 while(par[i]>=0) i=par[i]; 18 while(j!=i) { 19 temp=par[j]; 20 par[j]=i; 21 j=temp; 22 } 23 return i; 24 } 25 bool unite(int x,int y) { 26 int p=getroot(x); 27 int q=getroot(y); 28 if(p==q)return false; 29 if(par[p]>par[q]) { 30 par[q]+=par[p]; 31 par[p]=q; 32 num[q]+=num[p]; 33 } else { 34 par[p]+=par[q]; 35 par[q]=p; 36 num[p]+=num[q]; 37 } 38 return true; 39 } 40 }gx; 41 int main(){ 42 int n,m,op,x,y; 43 while(~scanf("%d%d",&n,&m),n|m){ 44 gx.init(); 45 while(m--){ 46 scanf("%d",&op); 47 if(!op) continue; 48 scanf("%d",&x); 49 op--; 50 while(op--){ 51 scanf("%d",&y); 52 gx.unite(x,y); 53 } 54 } 55 printf("%d\n",gx.getnum(0)); 56 } 57 return 0; 58 }
end