POJ 2524 Ubiquitous Religions (并查集)

原题链接:Ubiquitous Religions

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

题目分析:典型的并查集模版题,这里就不详细叙述了。对算法本身不太了解的可以参考这篇文章:并查集算法详解


代码如下:

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

const int MAX = 50000;
int father[MAX];

int getfather(int v) {
    if (father[v] == v)
        return v;
    else
    {
        father[v] = getfather(father[v]); //路径压缩
        return father[v];
    }
}

void Union(int x,int y) {
    int fx = getfather(x);
    int fy = getfather(y);
    if(fy != fx)
        father[fx] = fy;
}

void init(int n) {
	for (int i = 0; i < n; i++) 
		father[i] = i;
}

int main() {
	int m, n, a, b, flag = 1;
	while (cin >> n >> m && m + n != 0) {
		memset(father, 0, sizeof(father));
		init(n);
		
		for (int i = 0; i < m; i++) {
			cin >> a >> b;
			Union(a, b);
		}
		
		int ans = 0;
		for (int i = 0; i < n; i++) 
			if (father[i] == i)
				ans++;
				
		cout << "Case " << flag++ << ": "<< ans << endl;
	}
}

猜你喜欢

转载自blog.csdn.net/laugh12321/article/details/81707837