摘要:
并查集模板——路径压缩,按秩分配
问题简述(问题转化):
有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;
}