题目链接 Balancing Act
就是求一棵树的重心,然后统计答案。
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 #define REP(i,n) for(int i(0); i < (n); ++i) 6 #define for_edge(i,x) for(int i = H[x]; i; i = X[i]) 7 8 const int INF = 1 << 30; 9 const int N = 100000 + 10; 10 11 int H[N << 1], E[N << 1], X[N << 1]; 12 int T, et, n, x, y; 13 int son[N]; 14 int ans_size, ans; 15 16 inline void addedge(int a, int b){ 17 E[++et] = b, X[et] = H[a], H[a] = et; 18 E[++et] = a, X[et] = H[b], H[b] = et; 19 } 20 21 void dfs(int x, int fa){ 22 int sn = 0; 23 for_edge(i, x){ 24 int u = E[i]; 25 if (u != fa){ 26 dfs(u, x); 27 son[x] += son[u]; 28 sn = max(sn, son[u]); 29 } 30 } 31 ++son[x]; 32 sn = max(sn, n - son[x]); 33 if (ans_size > sn || ans_size == sn && ans > x){ 34 ans_size = sn; 35 ans = x; 36 } 37 38 } 39 40 int main(){ 41 42 scanf("%d", &T); 43 for (; T--;){ 44 ans_size = INF; ans = INF; 45 memset(H, 0, sizeof H); 46 memset(son, 0, sizeof son); 47 et = 0; 48 scanf("%d", &n); 49 REP(i, n - 1){ 50 scanf("%d%d", &x, &y); 51 addedge(x, y); 52 } 53 dfs(1, 0); 54 printf("%d %d\n", ans, ans_size); 55 } 56 57 return 0; 58 59 }
时间: 2024-12-21 12:27:11