poj1611 The Suspects(并查集)

时间:2022-01-27 03:14:33

题目链接

http://poj.org/problem?id=1611

题意

有n个学生,编号0~n-1,m个社团,每个社团有k个学生,如果社团里有1个学生是SARS的疑似患者,则该社团所有人都要被隔离。起初学生0是疑似患者,求要隔离多少人。

思路

使用并查集求解。

代码

 #include <iostream>
#include <cstring>
#include <cstdio>
using namespace std; const int N = + ;
int p[N]; void make_set(int n)
{
for (int i = ; i < n; i++)
p[i] = i;
} int find_root(int x)
{
if (x == p[x])
return x;
else
{
int temp = find_root(p[x]); //路径压缩
p[x] = temp;
return temp;
}
} void union_set(int x, int y)
{
int px = find_root(x);
int py = find_root(y);
if (px != py)
p[px] = py;
} int main()
{
freopen("poj1611.txt", "r", stdin);
int n, m;
while (scanf("%d%d", &n,&m)== && n)
{
make_set(n);
for (int i = ; i < m; i++)
{
int k;
int x, y;
scanf("%d%d", &k, &x);
for (int j = ;j < k;j++)
{
scanf("%d", &y);
union_set(x, y);
x = y;
}
}
int root = find_root();
int ans = ;
for (int i = ; i < n; i++)
if (find_root(i) == root)
ans++;
cout << ans << endl;
}
return ;
}