思路:删除根结点,其最大子树的节点最少。求一次树的重心即可。
AC代码
#include <cstdio>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define eps 1e-10
#define inf 0x3f3f3f3f
#define PI pair<int, int>
typedef long long LL;
const int maxn = 5e4 + 5;
vector<int>G[maxn];
int ans, n;
int dfs(int u, int pre) {
int cnt = 0, maxt = 0;
for(int i = 0; i < G[u].size(); ++i) {
int v = G[u][i];
if(v == pre) continue;
int d = dfs(v, u);
cnt += d;
maxt = max(maxt, d);
}
maxt = max(maxt, n - cnt - 1);
ans = min(ans, maxt);
return cnt + 1;
}
int main() {
while(scanf("%d", &n) == 1) {
for(int i = 1; i <= n; ++i) G[i].clear();
int u, v;
for(int i = 0; i < n-1; ++i) {
scanf("%d%d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
ans = inf;
dfs(1, -1);
printf("%d\n", n - ans);
}
return 0;
}
如有不当之处欢迎指出!