一道并查集的题,找出多余数据的数量(就是如果找到一个数据,之前存储过了,就不存储,输出多余数据数量)
我的代码如下(但是错了,是东方的题:网址 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;
}
求解答