这道题用并查集效率很高。
![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)
#include<iostream>
#include<string.h>
#include<fstream>
using namespace std;
int n,m;
int students[30000];
int find(int f)
{
int p=f;
while(p!=0&&students[p]>=0)
p=students[p];
while(p!=0&&students[f]>=0)
{
int temp=students[f];
students[f]=p;
f=temp;
}
return p;
}
void uni(int f1,int f2)
{
int r1=find(f1);
int r2=find(f2);
if(r1==r2)
return;
if(students[r1]==0||students[r2]==0)
{
if(students[r1]==0)
{
students[r2]=r1;
}
else
{
students[r1]=r2;
}
}
else
{
if(students[r1]<=students[r2])
{
students[r1]+=students[r2];
students[r2]=r1;
}
else
{
students[r2]+=students[r1];
students[r1]=r2;
}
}
}
int main()
{
freopen("input.txt","r",stdin);
while(scanf("%d %d",&n,&m)!=EOF)
{
if(m==0&&n==0)
break;
memset(students,-1,sizeof(int)*n);
students[0]=0;
for(int i=0;i<m;i++)
{
int k;
scanf("%d",&k);
int first;
scanf("%d",&first);
for(int j=1;j<k;j++)
{
int temp;
scanf("%d",&temp);
uni(first,temp);
}
}
int count=0;
for(int i=0;i<n;i++)
{
if(find(i)==0)
count++;
}
printf("%d\n",count);
}
return 0;
}