题解:AT_abc399_c [ABC399C] Make it Forest

· · 题解

C. Make it Forest

【题意简述】

给定一个有 N 个结点,M 条边的简单无向图,求最少需要删除几条无向边,使这个无向图成为一个森林。

## 【思路分析】 考虑使用并查集。 初始令答案 $ans \gets 0$。 每次读入一条边,判断这条边连接的两个部分是否连通。如果不联通,在并查集中归并这两个部分。如果连通,说明不需要这条边,令 $ans \gets ans + 1$。 最后输出 $ans$。 ## 【AC Code】 ```C++ /* 书本试卷堆积的角落里 找到没贴邮票泛黄的信 不禁幻想回到那个雨季 说出 反复练习 却没说的话语 —— 鸽稀拉 《回信》 In the corner where books and test papers are piled up Found a yellowed letter without a stamp I can't help but fantasize about returning to that rainy season "Saying words that have been repeatedly practiced but not spoken" - Reply (by Gexila) */ #include <bits/stdc++.h> #define endl "\n" #define int long long using namespace std; const int N = 2e5 + 5; int a[N], pre[N]; int n, m; int ans; int root(int x) { return pre[x] = (pre[x] == x ? x : root(pre[x])); } void merge(int x, int y) { pre[root(x)] = root(y); } bool check(int x, int y) { return root(x) == root(y); } signed main() { ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); cin >> n >> m; for (int i = 1; i <= n; i++) { pre[i] = i; } for (int i = 1; i <= m; i++) { int u, v; cin >> u >> v; if (!check(u, v)) { merge(u, v); } else { ans++; } } cout << ans << endl; return 0; } /* By Terminal_P >_P Copyright 2025. All Rights Reserved. Luogu: Terminal_P Bilibili: Terminal_P Netease Music: Terminal_P QQ ID: 2705680938 QQ Group ID: 945817959 Nice to meet you. */ ``` [AC记录 Submission #64289834](https://atcoder.jp/contests/abc399/submissions/64289834)