您的位置:首页 > 其它

[POJ1611]The Suspects(并查集)

2017-06-15 14:38 351 查看

传送门

 

通过并查集统计集合个数,easy

 

——代码

#include <cstdio>
#include <iostream>
#define N 1000001

int n, m;
int f
, num
;

inline int read()
{
int x = 0, f = 1;
char ch = getchar();
for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1;
for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0';
return x * f;
}

inline int find(int x)
{
return x == f[x] ? x : f[x] = find(f[x]);
}

inline void connect(int x, int y)
{
x = find(x);
y = find(y);
if(x ^ y) f[x] = y, num[y] += num[x];
}

int main()
{
int i, j, k, x, y;
while(~scanf("%d %d", &n, &m))
{
if(!n && !m) break;
for(i = 0; i <= n; i++) f[i] = i, num[i] = 1;
for(i = 1; i <= m; i++)
{
k = read();
if(k) y = read();
for(j = 2; j <= k; j++)
{
x = read();
connect(x, y);
y = x;
}
}
printf("%d\n", num[find(0)]);
}
return 0;
}
View Code

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: