原题链接: http://poj.org/problem?id=1611

测试样例
Sample Input
 100 4
 2 1 2
 5 10 13 11 12 14
 2 0 1
 2 99 2
 200 2
 1 5
 5 1 2 3 4 5
 1 0
 0 0
 Sample Output
 4
 1
 1
题意: 有个学生和
个小组,其中每个学生可以加入多个小组。学生编号从
到
,现在有一个规定,若一个小组中有一个是疑似SARS感染者,那么该小组其他人也会被认为是SARS感染者。现在学生
被认为是SARS感染者,你需要找出这
个学生中到底有多少个
感染者。
解题思路: 一道妥妥的并查集问题,即小组的同为一集合,一个人待的多个小组也是同一集合,这样去合并即可,最后计算与编号为的同学所在的集合有多少就行。要注意的一点就是我们在进行小组合并时可以选择一个主导者作为参考者,让其他组员加入他所在的集合。 OK,具体看代码。
AC代码
/*
*
*
*/
//POJ不支持
//i为循环变量,a为初始值,n为界限值,递增
//i为循环变量, a为初始值,n为界限值,递减。
using namespace std;
const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 3e4+4;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll>  pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//
int n,m;//n代表人数,m代表组数。
int father[maxn];//每个人所在集合。
int Find(int x){
  int r=x;
  while(r!=father[r]){
    r=father[r];
  }
  int i=x,j;
  while(father[i]!=r){
    j=father[i];
    father[i]=r;
    i=j;
  }
  return r;
}
int main(){
  //freopen("in.txt", "r", stdin);//提交的时候要注释掉
  IOS;
  while(cin>>n>>m){
    if(n==0&&m==0){
      break;
    }
    rep(i,0,n-1){
      father[i]=i;
    }
    rep(i,0,m-1){
      //默认第一个组为老大。
      int temp,leader,people;
      cin>>temp;
      if(temp==0){
        continue;
      }
      cin>>leader;
      rep(i,1,temp-1){
        cin>>people;
        int fx=Find(leader);
        int fy=Find(people);
        if(fx!=fy){
          father[fy]=fx;
        }
      }
    }
    int cnt=0;
    rep(i,0,n-1){
      if(Find(i)==Find(0)){
        cnt++;
      }
    }
    cout<<cnt<<endl;
  }
  return 0;
}                
                










