https://www.acwing.com/problem/content/848/

输出将重心删除后,剩余各个连通块中点数的最大值。
时间复杂度:\(O(n)\),极限 \(O(n^2)\)

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
vector <int> g[N];
int n, ans = 1e9, st[N];
int dfs(int u){
	st[u] = 1;
	int s = 1, res = 0;
	for (auto v : g[u]){
		if (!st[v]){
			int t = dfs(v);
			res = max(res, t);
			s += t;
		}
	}
	res = max(res, n - s);
	ans = min(ans, res);
	return s;
}
int main(){
	ios::sync_with_stdio(false);cin.tie(0);
	cin >> n;
	for (int i = 1; i < n; i ++ ){
		int u, v;
		cin >> u >> v;
		g[u].push_back(v);
		g[v].push_back(u);
	}
	dfs(1);
	cout << ans << "\n";
	return 0;
}
posted on 2022-04-25 16:04  Hamine  阅读(13)  评论(0编辑  收藏  举报