并查集

可以解决生成最小生成树Kruskal算法。

#include<iostream>
#include<cstdio>

using namespace std;

int parent[100010];

int find(int x)
{
	if (parent[x] != x)
	{
		return  find(parent[x]);
	}
	else
		return parent[x];
}
int main()
{
	freopen("input.txt", "r", stdin);
	int n, m, k;
	scanf("%d%d%d", &n, &m, &k);
	for (int i = 1; i <= n; ++i)
		parent[i] = i;
	for (int i = 0; i < m; i++)
	{
		int x, y;
		scanf("%d%d", &x, &y);
		y = find(y);
		x = find(x);
		parent[x] = y;

	}
	//for (int i = 1; i <= n; i++)
	//	cout << parent[i] << ' ';
	for (int i = 0; i < k; i++)
	{
		int x, y;
		scanf("%d%d", &x, &y);
		int px = find(x);
		int py = find(y);
		if (px == py)
			printf("yes\n");
		else
			printf("no\n");
	}
	system("pause");

}


并查集用来解决不相交集合之间合并及查询问题。

你可能感兴趣的:(C++,算法,ACM,kruskal,并查集)