poj1161 The Suspects

并查集

#include<iostream>
using namespace std;

#define N 30000
#define G 501
int p[N], group[N];

int main()
{
    int n, g;
    while(scanf("%d %d", &n, &g) == 2)
    {
                    if(n + g == 0) break;
                    int i,j,k;
                    for(i=0; i<n; i++)
                    p[i] = i;
                    
                    for(i=0; i<g; i++)
                    {
                             int gn;
                             scanf("%d", &gn);
                             for(j=0; j<gn; j++)
                             scanf("%d", &group[j]);
                             
                             int Min = N;
                             for(j=0; j<gn; j++)
                             {
                                      int t = group[j];
                                      while(t != p[t]) t = p[t];
                                      if(Min > t) Min = t;
                                      }

                             for(j=0; j<gn; j++)
                             {
                                      int t = group[j];

                                      while(p[t] != t)  t = p[t], p[t] = Min;
                                      p[t] = Min;
                                      }
                             }
                             int res = 0;
                             for(i=0; i<n; i++)
                             {
                                      int t =  p[i];
                                      while(p[t] != t) t = p[t];
                                      if(t == 0) res ++;                               
                                      }
                             printf("%d\n", res);

                             }
    return 0;
    }


你可能感兴趣的:(poj1161 The Suspects)