HOJ 1213 How Many Tables 并查集入门题

一个简单的并查集题目,暴力解决。

我这里只用一维数组,时间复杂度为O(n*m),n为人数,m为给定的关系个数。
#include<iostream>
#include<cstring>
#include<algorithm>
#pragma warning(disable: 4996)
using namespace std;
const int NN = 1000 + 5;
int a[NN];

int main()
{
	int t, n, m, x, y, num;
	cin >> t;
	while (t--)
	{
		num = 1;
		cin >> n >> m;
		for (int i = 0; i <= n; i++)
			a[i] = i;
		for (int i = 0; i < m; i++)
		{
			scanf("%d %d", &x, &y);
			x = a[x];
			y = a[y];
			for (int j = 1; j <= n; j++)
				if (a[j] == x || a[j] == y)
					a[j] = x;
		}
		sort(a + 1, a + n + 1);//排好序直接看有多少各不同“类别”的,就是多少个集合
		for (int i = 2; i <= n; i++)
			if (a[i] != a[i - 1])
				num++;
		cout << num << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44724908/article/details/104157133