Tree-type DP.
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#defineMAXV 200500#defineMaxe 300500#defineINF 1000000007using namespacestd;Long LongN,x,y,z,c[maxv],nume=0, g[maxv],val[maxv],sum=0, ANS,DIS[MAXV];structedge{Long LongV,W,NXT;} E[maxe];voidAddedge (Long LongULong LongVLong LongW) {e[++nume].v=v; E[NUME].W=W; E[NUME].NXT=G[u]; G[u]=Nume;}voidDFS1 (Long LongXLong LongFath) {Val[x]=C[x]; for(Long LongI=g[x];i;i=e[i].nxt) { Long Longv=e[i].v; if(v!=Fath) {Dis[v]=dis[x]+E[I].W; DFS1 (V,X); VAL[X]+=Val[v]; } }}voidDFS2 (Long LongXLong LongFathLong LongNow ) { for(Long LongI=g[x];i;i=e[i].nxt) { Long Longv=e[i].v; if(v!=Fath) { Long Longre=now-val[v]*e[i].w+ (Sum-val[v]) *E[I].W; Ans=min (ans,re); DFS2 (V,x,re); } }}intMain () {scanf ("%lld",&N); for(Long LongI=1; i<=n;i++) {scanf ("%lld",&C[i]); Sum+=C[i]; } for(Long LongI=1; i<=n-1; i++) {scanf ("%lld%lld%lld",&x,&y,&z); Addedge (x, y, z); Addedge (Y,X,Z); } DFS1 (1,1); for(Long LongI=1; i<=n;i++) ans+=c[i]*Dis[i]; DFS2 (1,1, ans); printf ("%lld\n", ans); return 0;}
Bzoj 1827 Big Cow Rally