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
论使用scanf和printf的重要性
(第一行是cin cout加关闭同步,第二行是直接cin cout,第三行是scanf和printf)
(左边那列是time 中间是memory)
代码:
#include <stdio.h>
using namespace std;
int const N = 3e4+10;
int union_map[N];
int n,m;
int find_root(int curr)
{
return curr==union_map[curr]?curr:union_map[curr]=find_root(union_map[curr]);
}
int main()
{
while(scanf("%d%d", &n, &m)&& (n || m))
{
for(int i=0;i<=n;i++)
union_map[i]=i;
for(int i=0;i<m;i++)
{
int num;
scanf("%d",&num);
int x,y;
for(int j=1;j<=num;j++)
{
scanf("%d", &y);
if (j == 1) {
x = y;
continue;
}
int tx = find_root(x);
int ty = find_root(y);
if(tx>ty)
union_map[tx]=ty;
else
union_map[ty] = tx;
}
}
int counter=0;
for(int i=0;i<n;i++)
{
if(0==find_root(i))
counter++;
}
printf("%d\n", counter);
}
return 0;
}