跳到正文

题解

题解:AT_abc399_c [ABC399C] Make it Forest

AFO_Lzx约 2 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v1当前

题目传送门

Description\texttt{Description}

给定一个 nn 个顶点 mm 条边的简单无向图,问如果要将这个无向图变为一个森林,即为不含任何环的简单无向图,至少需要删去多少条边。

Solution\texttt{Solution}

本题需要使用并查集来解决,这里放上模板题和 oi.wiki 上对于并查集的介绍。

实际上我们每次只需要判断输入的边的两个顶点 uu 和 vv 是否在一个集合当中,如果已经在一个集合当中,那么添加这条边就会形成一个环,所以需要删除这条边。否则的话就是将 uu 和 vv 合并到一个集合当中。

Code\texttt{Code}

C++
#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;
}
原文