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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
|
#include <cstdio> #include <vector> #include <algorithm>
using namespace std;
int fa[200005]; int deg[200005]; vector<int> ch[200005], near[200005];
void dfs(int u, int ffa = 0) { auto it = find(ch[u].begin(), ch[u].end(), ffa); if (it != ch[u].end()) { ch[u].erase(it); } fa[u] = ffa; for (int v : ch[u]) dfs(v, u); }
bool mark[200005]; int get_cent(int u) { while (fa[u] && !mark[fa[u]]) u = fa[u]; int total_sz = 0; auto calc_totalsz = [&](auto self, int u) -> void { total_sz++; for (int v : ch[u]) if(!mark[v]) self(self, v); }; calc_totalsz(calc_totalsz, u); auto get_cent = [&](auto self, int u) -> int { int sum = 1, maxn = 0; for (int v : ch[u]) if(!mark[v]) { int res = self(self, v); if (res < 0) return res; sum += res; if (res > maxn) maxn = res; } if (total_sz - sum > maxn) maxn = total_sz - sum; if (maxn <= total_sz / 2) return -u; return sum; }; return -get_cent(get_cent, u); }
int solve(int u) { u = get_cent(u); mark[u] = true; int l3 = -0x3f3f3f3f, maxn = 1; if (deg[u] >= 3) l3 = 0; for (int v : near[u]) { if (!mark[v]) { auto cal_it = [&](auto self, int u, int len, int lst) -> void { if (deg[u] >= 3 && len + l3 + 1 > maxn) maxn = len + l3 + 1; if (deg[u] >= 4) { for (int v : near[u]) { if (!mark[v] && v != lst) self(self, v, len + 1, u); } } }; cal_it(cal_it, v, 1, u); if (deg[u] >= 4) { auto update_it = [&](auto self, int u, int len, int lst) -> void { if (deg[u] >= 3 && len > l3) l3 = len; if (deg[u] >= 4) { for (int v : near[u]) { if (!mark[v] && v != lst) self(self, v, len + 1, u); } } }; update_it(update_it, v, 1, u); } } } for (int v : near[u]) { if (!mark[v]) { int res = solve(v); if (res > maxn) maxn = res; } } return maxn; }
int main() { int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) { deg[i] = 0; ch[i].clear(); near[i].clear(); fa[i] = 0; mark[i] = false; } for (int i = 2; i <= n; i++) { int u, v; scanf("%d%d", &u, &v); ch[u].push_back(v); ch[v].push_back(u); near[u].push_back(v); near[v].push_back(u); deg[u]++; deg[v]++; } dfs(1); printf("%d\n", solve(1)); } return 0; }
|