HDU - 1213 并查集果题

原题:
多少张桌子?

完全就是并查集的模板。。
没什么好说的,直接套模板。。
如果看不懂并查集的,建议看一下我之前写的题目入门一下。。
题目:
畅通工程
嫌疑人

AC代码:

#include<iostream>
using namespace std;
int parent[1005];
void united(int, int);
int find_root(int);
int text;

int main()
{
	cin >> text;
	while (text--)
	{
		int mum, text2;
		cin >> mum >> text2;
		for (int i = 1; i <= mum; i++)
		{
			parent[i] = i;
		}
		while (text2--)
		{
			int m, n;
			cin >> m >> n;
			united(m, n);
		}
		int sum = 0;
		for (int i = 1; i <= mum; i++)
		{
			if ( parent[i] == i )
			{
				sum++;
			}
		}
		cout << sum << endl;
	}
	return 0;
}

int find_root(int x)
{
	if (parent[x] == x)
		return x;
	else
		return parent[x] = find_root(parent[x]);
}

void united(int x, int y)
{
	int xx, yy;
	xx = find_root(x);
	yy = find_root(y);
	if (xx != yy)
	{
		parent[yy] = xx;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_26558047/article/details/86663708