| Time Limit: 5000MS | Memory Limit: 65536KB | 64bit IO Format: %I64d & %I64u |
Description
Input
Output
Sample Input
10 9 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 10 4 2 3 4 5 4 8 5 8 0 0
Sample Output
Case 1: 1 Case 2: 7
Hint
简单并查集,求无向图连通分量。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN = 50000 + 50;
int parent[MAXN];
int n, m;
void make_set()
{
for (int i = 0; i <= n; i++)
parent[i] = -1;
}
int find_set(int t)
{
if (parent[t] == -1)
return t;
else
return parent[t] = find_set(parent[t]);
}
void union_set(int a, int b)
{
int t1 = find_set(a);
int t2 = find_set(b);
if (t1 != t2)
parent[t2] = t1;
}
int main()
{
int casen;
casen = 1;
while (scanf("%d%d", &n, &m) != EOF&&n)
{
int a, b;
make_set();
for (int i = 0; i < m; i++)
{
scanf("%d%d", &a, &b);
union_set(a, b);
}
int sum = 0;
for (int i = 1; i <= n; i++)
{
if (parent[i] == -1)
sum++;
}
printf("Case %d: ", casen);
casen++;
printf("%d\n", sum);
}
}版权声明:本文为博主原创文章,未经博主允许不得转载。
POJ - 2524 Ubiquitous Religions(简单并查集)
原文地址:http://blog.csdn.net/qq_18738333/article/details/47978147