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
| #include <bits/stdc++.h> using namespace std; const int N = 3e5 + 5; int n; vector<int> G[N]; int dep[N]; namespace LCA { const int Lg = 19; int ST[Lg][N],lg[N]; int dfn[N]; int Min(int x,int y) { return dfn[x] < dfn[y] ? x : y;} void dfs(int x,int fa) { ST[0][dfn[x] = ++dfn[0]] = fa; for(auto y : G[x]) if(y != fa) dep[y] = dep[x] + 1,dfs(y,x); } void init() { lg[0] = -1;dfn[0] = 0;dfs(1,0); for(int i = 1;i <= n;i++) lg[i] = lg[i >> 1] + 1; for(int j = 1;j < Lg;j++) for(int i = 1;i + (1 << j) - 1 <= n;i++) ST[j][i] = Min(ST[j - 1][i],ST[j - 1][i + (1 << j - 1)]); } int lca(int x,int y) { if(x == y) return x; x = dfn[x];y = dfn[y]; if(x > y) swap(x,y); int k = lg[y - (x++)]; return Min(ST[k][x],ST[k][y-(1<<k)+1]); } int dis(int x,int y) { return dep[x] + dep[y] - 2 * dep[lca(x,y)];} } vector<int> ps[N],S; int pxu = -1,pxv = -1; void Add_n(int i) { if(pxu == -1) {pxu = pxv = i;S.push_back(i);return;} S.push_back(i); int nu = pxu,nv = pxv; if(LCA::dis(pxu,i) > LCA::dis(nu,nv)) nu = pxu,nv = i; if(LCA::dis(pxv,i) > LCA::dis(nu,nv)) nu = i,nv = pxv; pxu = nu;pxv = nv; } int GetDis() { if(pxu == -1) return -1e9; return (LCA::dis(pxu,pxv) + 1) >> 1; } void Change(int &Ans) { for(auto i : ps[Ans]) Add_n(i); --Ans; } int mxdep; int ans[N]; inline void Clr(int n) { mxdep = LCA::dfn[0] = 0;pxu = pxv = -1; for(int i = 0;i <= n;i++) G[i].clear(),ps[i].clear(),dep[i] = 0; } inline void work(){ cin >> n;Clr(n); for(int i = 1,u,v;i < n;i++) cin >> u >> v,G[u].push_back(v),G[v].push_back(u); LCA::init(); for(int i = 1;i <= n;i++) mxdep = max(mxdep,dep[i]),ps[dep[i]].push_back(i); int Ans = mxdep; for(int x = n;x >= 1;x--) { while(Ans >= 0 && GetDis() + x <= Ans) Change(Ans); ans[x] = Ans + 1; } for(int x = 1;x <= n;++x) cout << ans[x] << ' '; cout << endl; } int main() { int T; cin >> T; while(T--) work(); return 0; }
|