1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| #include <cstdio> #include <vector> #include <algorithm>
using namespace std; const int maxn = 1e4 + 10; int n; struct Node { int v, depth, bestD; vector<int> child; } G[maxn]; bool vis[maxn] = {false};
bool cmp(Node &a, Node &b) { if (a.bestD != b.bestD) return a.bestD > b.bestD; else return a.v < b.v; }
void dfs(int st) { if(G[st].depth>G[st].bestD){ G[st].bestD=G[st].depth; } vis[st] = true; for (int i = 0; i < G[st].child.size(); i++) { int next = G[st].child[i]; if (vis[next] == false) { G[next].depth = G[st].depth + 1; dfs(next); } } }
void dfs1(int st) { vis[st] = true; for (int i = 0; i < G[st].child.size(); i++) { int next = G[st].child[i]; if (vis[next] == false) { dfs1(next); } } }
int main() { scanf("%d", &n); int s, t; if (n==1) { printf("1"); return 0; } for (int i = 0; i < n - 1; i++) { scanf("%d%d", &s, &t); G[s].child.push_back(t); G[t].child.push_back(s); G[s].v = s; G[t].v = t; } for (int i = 1; i <= n; i++) { G[i].depth = 1; G[i].bestD = -1; } int com = 0; for (int i = 1; i <= n; i++) { if (vis[i] == false) { dfs1(i); com++; } } if (com > 1) { printf("Error: %d components", com); } else { for (int i = 1; i <= n; i++) { fill(vis, vis + maxn, false); for (int j = 1; j <= n; j++) { G[j].depth = 1; } dfs(i); } sort(G + 1, G + n + 1, cmp); for (int i = 1; i <= n; i++) { if (G[i].bestD == G[1].bestD) { printf("%d\n", G[i].v); } else break; } } return 0; }
|