【数据结构1-3】集合【持续更新中】

P1551 亲戚

题目链接:P1551 亲戚 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

#include <iostream>
using namespace std;
int fa[5005], Rank[5005];

int find(int x) {
	if (x == fa[x]) {
		return x;
	} else {
		fa[x] = find(fa[x]);
		return fa[x];
	}
}

void merge(int i, int j) {
	int x = find(i), y = find(j);
	if (Rank[x] <= Rank[y]) {
		fa[x] = y;
	} else {
		fa[y] = x;
	}
	if (Rank[x] == Rank[y] && x != y) {
		Rank[y]++;
	}
}

int main() {
	int n, m, p, x, y;
	cin >> n >> m >> p;
	for (int i = 1; i <= n; i++) {
		fa[i] = i;
		Rank[i] = 1;
	}
	for (int i = 0; i < m; i++) {
		cin >> x >> y;
		merge(x, y);
	}
	for (int i = 0; i < p; i++) {
		cin >> x >> y;
		if (find(x) == find(y)) {
			cout << "Yes" << endl;
		} else {
			cout << "No" << endl;
		}
	}
	return 0;
}

参考博客:算法学习笔记(1) : 并查集 - 知乎 (zhihu.com) 

error: reference to 'rank' is ambiguous_荷叶田田-CSDN博客 

上一篇:tornado 异步调用系统命令和非阻塞线程池


下一篇:只需四步,帮助企业做好MaxCompute成本优化