跳到正文

题解

题解:AT_abc399_c [ABC399C] Make it Forest

Terminal_P约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年3月30日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 3 分钟

版本

  1. v1当前

C. Make it Forest

【题意简述】

给定一个有 NN 个结点,MM 条边的简单无向图,求最少需要删除几条无向边,使这个无向图成为一个森林。
1≤N≤2×105,0≤M≤min⁡{N(N−1)2,2×105}1 \le N \le 2 \times 10^5, 0 \le M \le \min\left\{\frac{N(N - 1)}{2}, 2\times 10^5\right\}。

【思路分析】

考虑使用并查集。
初始令答案 ans←0ans \gets 0。
每次读入一条边,判断这条边连接的两个部分是否连通。如果不联通,在并查集中归并这两个部分。如果连通,说明不需要这条边,令 ans←ans+1ans \gets ans + 1。
最后输出 ansans。

【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

原文