bzoj2435: [Noi2011]道路修建
树形dp,bfs。 dfs爆栈。
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; const int maxn = 1000000 + 10; const int maxm = 2000000 + 10; int g[maxn],v[maxm],next[maxm],c[maxm],eid; int q[maxn],f[maxn],t[maxn],size[maxn]; int n; long long res; void addedge(int a,int b,int C) { v[eid]=b; next[eid]=g[a]; c[eid]=C; g[a]=eid++; v[eid]=a; next[eid]=g[b]; c[eid]=C; g[b]=eid++; } void bfs() { int l=1,r=1; q[r++]=1; while(l<r) { int u=q[l++]; size[u]=1; for(int i=g[u];~i;i=next[i]) if(v[i]!=f[u]) { f[v[i]]=u; t[v[i]]=c[i]; q[r++]=v[i]; } } } int ab(int a,int b) { int res=a-b; if(res<0) return -res; else return res; } int main() { scanf("%d",&n); memset(g,-1,sizeof(g)); for(int i=1,u,v,C;i<=n-1;i++) { scanf("%d%d%d",&u,&v,&C); addedge(u,v,C); } bfs(); for(int i=n,u;i>1;i--) { u=q[i]; size[f[u]]+=size[u]; res+=(long long)t[u]*ab(size[u],n-size[u]); } printf("%lld\n",res); return 0; }