前言:准确理解题意并转化,也是非常重要的一步。
dsu on tree裸题。
对于静态链分治的理解,更加深刻了一些,对于mx等有影响的参数。
在处理轻儿子时,也需要清空,这才是真正意义上的清空操作。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// Author: levil #include<bits/stdc++.h> using namespace std; typedef long long LL; typedef pair<string,int> pii; const int N = 1e6+5; const int M = 1e5+5; const LL Mod = 199999; #define rg register #define pi acos(-1) #define INF 1e9 #define CT0 cin.tie(0),cout.tie(0) #define IO ios::sync_with_stdio(false) #define dbg(ax) cout << "now this num is " << ax << endl; namespace FASTIO{ inline LL read(){ LL x = 0,f = 1;char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -1;c = getchar();} while(c >= '0' && c <= '9'){x = (x<<1)+(x<<3)+(c^48);c = getchar();} return x*f; } void print(int x){ if(x < 0){x = -x;putchar('-');} if(x > 9) print(x/10); putchar(x%10+'0'); } } using namespace FASTIO; void FRE(){/*freopen("data1.in","r",stdin); freopen("data1.out","w",stdout);*/} int n,ssize[N],son[N],dep[N],Son,d[N],ans[N],mx = 0,ma; vector<int> G[N]; void dfs(int u,int fa) { ssize[u] = 1,dep[u] = dep[fa]+1; for(auto v : G[u]) { if(v == fa) continue; dfs(v,u); ssize[u] += ssize[v]; if(ssize[v] > ssize[son[u]]) son[u] = v; } } void slove(int u,int fa,int val) { d[dep[u]] += val; if(d[dep[u]] > mx) mx = d[dep[u]],ma = dep[u]; if(d[dep[u]] == mx && dep[u] < ma) ma = dep[u]; for(auto v : G[u]) { if(v == fa || v == Son) continue; slove(v,u,val); } } void dfs1(int u,int fa,int opt) { for(auto v : G[u]) { if(v == fa || v == son[u]) continue; dfs1(v,u,0); } if(son[u]) dfs1(son[u],u,1),Son = son[u]; slove(u,fa,1); ans[u] = ma-dep[u]; Son = 0; if(opt == 0) slove(u,fa,-1),mx = ma = 0; } int main() { n = read(); for(rg int i = 1;i < n;++i) { int x,y;x = read(),y = read(); G[x].push_back(y); G[y].push_back(x); } dfs(1,0); dfs1(1,0,0); for(rg int i = 1;i <= n;++i) printf("%d ",ans[i]); system("pause"); }