并查集 求助
  • 板块灌水区
  • 楼主__Rickysun__
  • 当前回复6
  • 已保存回复6
  • 发布时间2024/1/26 20:00
  • 上次更新2024/1/26 21:37:26
查看原帖
并查集 求助
824205
__Rickysun__楼主2024/1/26 20:00

一道并查集的题,找出多余数据的数量(就是如果找到一个数据,之前存储过了,就不存储,输出多余数据数量) 我的代码如下(但是错了,是东方的题:网址 https://oj.czos.cn/p/2427)

#include<bits/stdc++.h>
using namespace std;
int f[100010], n, k;
int find(int x) {
	if (f[x] == x) return x;
	else return f[x] = find(f[x]);
}
void merge(int x, int y) {
	int fx = find(x), fy = find(y);
	if (fx != fy) f[fx] = fy;
}
int main() {
	int x, y, cnt = 0;
	cin >> n >> k;
	for (int i = 1; i <= n; i++) {
		f[i] = i;
	}
	for (int i = 1; i <= k; i++) {
		cin >> x >> y;
		if (f[x] == f[y]) cnt++;
		else merge(x, y);
	}
	cout << cnt;
	return 0;
}

求解答

2024/1/26 20:00
加载中...