您的位置:首页 > 产品设计 > UI/UE

poj2524 Ubiquitous Religions(并查集)

2017-11-30 22:18 621 查看

题目链接

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

题意

有n个学生,编号1~n,每个学生最多有1个宗教信仰,输入m组数据,每组数据包含a、b,表示同学a和同学b有相同的信仰,求在n名学生中最多存在多少种不同的宗教信仰。

思路

使用并查集解决。

代码

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

const int N = 50000 + 10;
int p
;

void make_set(int n)
{
for (int i = 1;i <= n;i++)
p[i] = -1;
}

int find_root(int i)
{
if (p[i] == -1)
return i;
else
{
int temp = find_root(p[i]);        //路径压缩
p[i] = temp;
return temp;
}
}

void union_set(int a, int b)
{
int ra = find_root(a);
int rb = find_root(b);
if (ra != rb)
p[ra] = rb;
}

int main()
{
//freopen("poj2524.txt", "r", stdin);
int n, m;
int cnt = 0;
while (scanf("%d%d", &n, &m) == 2 && n)
{
make_set(n);
int a, b;
for (int i = 0; i < m; i++)
{
scanf("%d%d", &a, &b);
union_set(a, b);
}
int ans = 0;
for (int i = 1;i <= n;i++)
if (p[i] == -1) ans++;
printf("Case %d: %d\n", ++cnt, ans);
}
return 0;
}

 

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