并查集,转载

https://blog.csdn.net/niushuai666/article/details/6662911

原文大佬的位置,这里总结一下我学到的东西

首先理解起来,我个人而言花了一点时间可能是个人的智商问题

然后代码

#include<bits/stdc++.h>
using namespace std;

int pre[1000],total;

int find(int x)
{
	int son = x,temp;
	while (x != pre[x])
	{
		x = pre[x];
	}
	while (son != x)
	{
		temp = pre[son];
		pre[son] = x;
		son = temp;
	}
	return x;
}

void join(int x1, int x2)
{
	int x, y;
	x = find(x1);
	y = find(x2);
	if (x != y)
	{
		pre[x] = y;
		total--;
	}
}
int main()
{
	int num, road;
	cin >> num >> road;
	total = num;
	for (int i = 1; i <= num; i++)
	{
		int start, end;
		cin >> start >> end;
		join(start, end);
	}
	cout << total;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/yang8627/article/details/88299143
今日推荐