2021-02-26洛谷P1536并查集模板

15 篇文章 0 订阅
1 篇文章 0 订阅

摘要:

并查集模板——路径压缩,按秩分配


问题简述(问题转化):

有n个村庄,给出m个条件,每一个条件表示两个村庄之间相互连通。问给定的两个村庄之间是否可达(不一定是直接可达)
原题链接:洛谷P1536村村通


算法分析:

典型的并查集模板。可以使用路径压缩和按秩分配进行优化。
特别强调,本道题目中的输出不容易控制,可以采用表达式(cin>>n>>m)的返回值进行判断。使用cin进行输入,如果输入后缓冲区中没有其他东西(字符,整数等)责会返回EOF,EOF在while中被认为是false


代码以及详细注释:

#include <iostream>
#include <stdio.h>
#include <vector>
#pragma warning(disable:4996)
using namespace std;

class UnionFind {
public:
	int count;
	vector<int> root;
	vector<int> rank;
	UnionFind(int _count) :count(_count) {
		root.resize(_count + 1);
		for (int i = 1; i <= _count; ++i)
			root[i] = i;
		rank.resize(_count + 1, 0);
	}

	int find(int x) {
		return x == root[x] ? x : root[x] = find(root[x]);
	}

	void merge(int x, int y)
	{
		int rootx = find(x);
		int rooty = find(y);
		if (rootx != rooty) {
			if (rank[rootx] < rank[rooty])
				swap(rootx, rooty);
			root[rooty] = rootx;
			if (rank[rootx] == rank[rooty]) rank[rootx]++;
			--count;
		}
	}
};

int main() {
	//freopen("in.txt", "r", stdin);
	int n, m;
	while (cin >> n >> m)
	{
		int x, y;
		UnionFind u(n);
		for (int i = 1; i <= m; ++i)
		{
			cin >> x >> y;
			u.merge(x, y);
		}
		cout << u.count-1<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sentry-X

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值