首页 > 代码库 > poj 1611 The Suspects

poj 1611 The Suspects

并查集 简单题

 1 #include<cstdio> 2 #include<memory.h> 3 int par[1000]; 4 int Find(int x) 5 { 6     while(par[x] >= 0) 7         x = par[x]; 8     return x; 9 }10 void Merge(int x,int y)11 {12     int a,b;13     int tmp;14     a = Find(x);15     b = Find(y);16     if(a != b)17     {18         tmp = par[a] + par[b];19         if(a < b) //0 shi gan ran suoyi xiaode youxian20         {21             par[b] = a;22             par[a] = tmp;23         }24         else25         {26             par[a] = b;27             par[b] = tmp;28         }29     }30 }31 int main()32 {33     freopen("input.txt","r",stdin);34     int a,b,n,m,t;35     int cnt;36     while(scanf("%d%d",&n,&m) && n)//这里不能scanf("%d%d",&n,&m) && n && m) 因为m为0时同样可以37     {38 39         memset(par,-1,sizeof(par));40         while(m--)41         {42             scanf("%d",&t);43             scanf("%d",&a);44             t--;45             while(t--)46             {47                 scanf("%d",&b);48                 Merge(a,b);49             }50         }51 52         printf("%d\n",-par[0]);53     }54 }