题目分析
本题就是求每个节点的最小balance,如果有多个节点有相同的balance,那么输出最小的一个。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 2e4+5;
const int INF = 0x3f3f3f3f;
int head[maxn],siz[maxn],vis[maxn],balance[maxn],N,tot;
struct Edge{
int to,next;
}e[maxn<<1];
void addedge(int from, int to){
e[tot].to = to;
e[tot].next = head[from];
head[from] = tot++;
}
void dfs(int u){
siz[u] = 1;
vis[u] = 1;
for(int i = head[u]; i != -1; i = e[i].next){
int v = e[i].to;
if(!vis[v]){
dfs(v);
siz[u] += siz[v];
balance[u] = max(balance[u], siz[v]);
}
}
balance[u] = max(balance[u], N-siz[u]);
}
int main(){
int T;
scanf("%d", &T);
while(T--){
int from,to;
scanf("%d", &N);
tot = 0;
memset(head, -1, sizeof(head));
memset(vis, 0, sizeof(vis));
memset(balance, 0, sizeof(balance));
for(int i = 1; i < N; i++){
scanf("%d%d", &from, &to);
addedge(from, to);
addedge(to, from);
}
dfs(1);
int ans = INF,cnt;
for(int i = 1; i <= N; i++)
if(balance[i] < ans){
cnt = i;
ans = balance[i];
}
printf("%d %d\n", cnt, ans);
}
return 0;
}