HDU 1213 How Many Tables (并查集)

原题链接:How Many Tables

题目大意:Ignatiu 要邀请他的朋友们来参加他的生日聚会,这些朋友中有互相认识的,也有不认识的,若AB认识,BC认识,那么可以通过BAC也可当作互相认识。互相认识的朋友才可以坐在一桌,给出他们之间的认识情况,问邀请这么多朋友需要多少桌?

题目分析:这道题其实就是 POJ 2524 Ubiquitous Religions (并查集)的低配版,算是一道水题了。详细的思路就不再叙述了。(PS:对并查集算法还不了解的可以参考这篇文章: 并查集算法详解


代码如下:

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

const int MAX = 10000;
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, t;
	cin >> t;
	
	while (t--) {
		memset(father, 0, sizeof(father));
		cin >> n >> m;
		
		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 << ans << endl;
	}
	return 0;
}

猜你喜欢

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