您的位置:首页 > 其它

poj1611 The Suspects(并查集)

2017-11-30 21:44 393 查看

题目链接

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 = 30000 + 10;
int p
;

void make_set(int n)
{
for (int i = 0; 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)==2 && n)
{
make_set(n);
for (int i = 0; i < m; i++)
{
int k;
int x, y;
scanf("%d%d", &k, &x);
for (int j = 1;j < k;j++)
{
scanf("%d", &y);
union_set(x, y);
x = y;
}
}
int root = find_root(0);
int ans = 0;
for (int i = 0; i < n; i++)
if (find_root(i) == root)
ans++;
cout << ans << endl;
}
return 0;
}

 

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