题解:AT_abc399_c [ABC399C] Make it Forest
题目传送门
\texttt{Description}
给定一个
\texttt{Solution}
本题需要使用并查集来解决,这里放上模板题和 oi.wiki 上对于并查集的介绍。
实际上我们每次只需要判断输入的边的两个顶点
\texttt{Code}
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn = 2e5 + 5;
int n, m, ans, f[maxn];
int find(int x) {
if (f[x] == x) return x;
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;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) f[i] = i;
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
if (find(u) == find(v)) ans++; // 需要删除
else merge(u, v); // 合并
}
cout << ans << endl;
return 0;
}