大意: 给定有根树, 根节点深度为$1$.
定义$r(a,b)$为$b$子树内深度不超过$a$的节点数$-1$
定义$z_a$为$a$的所有祖先的$r$之和. 对于所有点求出$z$的值.
一个点$y$对$x$的贡献显然为$dep[lca(x,y)]$, 直接计算是$O(n^2logn)$, 考虑优化.
注意到点$y$对$x$子树内所有点贡献都相同, 我们考虑深度相同的点之间的贡献, 就转化为对下面程序的优化.
REP(d,1,n) q[dep[i]].push_back(d); REP(d,1,n) { for (int x:q[d]) for (int y:q[d]) { ans[x]+=dep[lca(x,y)]; } }
显然建出虚树然后DP即可, 复杂度为$O(nlogn)$
#include <iostream> #include <sstream> #include <algorithm> #include <cstdio> #include <math.h> #include <set> #include <map> #include <queue> #include <string> #include <string.h> #include <bitset> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl ' ' #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;}) using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;} inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;} //head #ifdef ONLINE_JUDGE const int N = 1e6+10; #else const int N = 111; #endif int n, rt, fa[N]; vector<int> g[N], q[N], gg[N]; int sz[N], dep[N], son[N]; int L[N], R[N], top[N]; ll ans[N], c[N]; void dfs(int x, int d) { L[x]=++*L,dep[x]=d,sz[x]=1; for (int y:g[x]) { dfs(y,d+1),sz[x]+=sz[y]; if (sz[y]>sz[son[x]]) son[x]=y; } R[x]=*L; } void dfs2(int x, int tf) { top[x]=tf; if (son[x]) dfs2(son[x],tf); for (int y:g[x]) if (!top[y]) dfs2(y,y); } int lca(int x, int y) { while (top[x]!=top[y]) { if (dep[top[x]]<dep[top[y]]) swap(x,y); x = fa[top[x]]; } return dep[x]<dep[y]?x:y; } void dfs(int x) { for (int y:g[x]) ans[y]+=ans[x],dfs(y); } int s[N], cnt; void DP1(int x) { sz[x]=gg[x].empty(); for (int y:gg[x]) DP1(y),sz[x]+=sz[y]; } void DP2(int x) { for (int y:gg[x]) c[y]=(ll)dep[x]*(sz[x]-sz[y])+c[x],DP2(y); } void solve(vector<int> a) { int sz = a.size(); sort(a.begin(),a.end(),[](int a,int b){return L[a]<L[b];}); REP(i,1,sz-1) a.pb(lca(a[i],a[i-1])); sort(a.begin(),a.end(),[](int a,int b){return L[a]<L[b];}); a.erase(unique(a.begin(),a.end()),a.end()); s[cnt=1]=a[0], sz = a.size(); REP(i,1,sz-1) { while (cnt>=1) { if (L[s[cnt]]<=L[a[i]]&&L[a[i]]<=R[s[cnt]]) { gg[s[cnt]].pb(a[i]); break; } --cnt; } s[++cnt]=a[i]; } DP1(s[1]),c[s[1]]=0,DP2(s[1]); for (int x:a) gg[x].clear(); } int main() { scanf("%d", &n); REP(i,1,n) scanf("%d",fa+i),g[fa[i]].pb(i); rt = min_element(fa+1,fa+1+n)-fa; dfs(rt,1),dfs2(rt,rt); REP(i,1,n) q[dep[i]].pb(i); REP(d,1,n) if (q[d].size()) { solve(q[d]); for (int x:q[d]) ans[x]=c[x]+dep[x]; } dfs(rt); REP(i,1,n) printf("%lld ", ans[i]-dep[i]);hr; }