ACM_并查集

//题意:ignatius过生日,客人来到,他想知道他需要准备多少张桌子。然而一张桌子上面只能坐上相互熟悉的人,
	//其中熟悉可定义成为A与B认识,B与C认识,我们就说A,B,C相互熟悉 。例如A与B熟悉and  B与C熟悉,D与E熟悉,此时至少需要两张桌子。
//输入:t表示样例个数,n表示朋友个数,朋友从1到n编号,m表示已知相互了解的对数,接着m行。每行表示相互熟悉的编号
//输出:至少需要准备的桌子个数

//刚学并查集!简单的并查集模板应用。 
 
#include <iostream>
using namespace std;

int pre[1010];

int find(int x)
{
	int r = x;
	while (pre[r] != r)
		r = pre[r];
	int i = x, j;
	while (i != r)
	{
		j = pre[i];
		pre[i] = r;
		i = j;
	}
	return r;
}

int main()
{
	int n, m;
	int t;
	cin >> t;
	while (t --)
	{
		int total; 
		cin >> n;
		for (int i = 1; i<=n; i++)
			pre[i] = i;
		total = n;
		cin >> m;
		int p1, p2, f1, f2;
		while (m --)
		{
			cin >> p1>> p2;
			f1 = find(p1);
			f2 = find(p2);
			if (f1 != f2)
			{
				pre[f2] = f1;
				total -- ;
			}
		}
		cout << total<< endl;
	}
	return 0;
}

原文地址:https://www.cnblogs.com/Tovi/p/6194852.html