Description
A tree that asks for the maximum sum of the root when the node is rooted.
Sol
Dfs+ tree-shaped DP.
For the first time, count size and D.
The second time transfer root, the statistical answer is OK.
Code
/************************************************************** problem:1131 User:beiyu language:c++ Result : Accepted time:8028 ms memory:78700 kb****************************************************************/#include &L t;cstdio> #include <vector> #include <iostream>using namespace std; typedef long LONG ll;const int N = 1000005; int N;int S[n],d[n]; LL Sd[n]; LL Ans1,ans2;int nxt[n<<1],gto[n<<1],e,h[n]; inline int in (int x=0,char Ch=getchar ()) {while (ch> ' 9 ' | | ch< ' 0 ') Ch=getchar (); while (ch>= ' 0 ' && ch<= ' 9 ') x=x*10+ch-' 0 ', Ch=getchar (); return x; } void Add_edge (int fr,int to) {nxt[++e]=h[fr],gto[e]=to,h[fr]=e;} void DFS1 (int u=1,int fa=0) {s[u]=1,sd[u]=d[u]=d[f a]+1; for (int i=h[u],v;i;i=nxt[i]) if ((V=gto[i])!=fa) {DFS1 (v,u), s[u]+=s[v],sd[u]+=sd[v]; }}void DFS2 (int u=1,int fa=1,ll x=0) {LL res=x+ (sd[u]-(LL) d[u]*s[u]);//cout<<u<< "" <<res<<en dl if (Ans2<res | | (ans2==res && ans1>u)) Ans1=u,ans2=res; for (int i=h[u],v;i;i=nxt[i]) if ((V=gto[i])!=fa) {DFS2 (v,u,x+n-s[v]+ (Sd[u]-sd[v])-(LL) d[u]* (S[u]-s[v])); }} int main () {//Freopen ("In.in", "R", stdin); N=in (); for (int i=1,u,v;i<n;i++) u=in (), V=in (), Add_edge (u,v), Add_edge (V,u); D[0]=-1; DFS1 (); ANS1=1,ANS2=SD[1]; DFS2 (); cout<<ans1<<endl; return 0;}
Bzoj 1131: [Poi2008]sta