See this problem feel very water , hit a recursive tree DP after re a group, and later found to be non-recursive (BFS)
Recursive version 84 points:
#include <cstdio>#include<cstring>#include<algorithm>using namespacestd;intn,point[1000003],next[2000003],v[2000003],c[2000003],cnt=0, f[1000003];BOOLp[1000003];Long Longsum=0;voidInsect (intXintYintZ) {next[cnt]=point[x];p oint[x]=cnt;v[cnt]=y;c[cnt]=z;cnt++;}voidDfsintx) { inti; F[X]=1; for(i=point[x];i!=-1; i=Next[i])if(p[v[i]]==0) {P[v[i]]=1; DFS (V[i]); F[X]+=F[v[i]]; Sum+ = (1ll*c[i]*abs (2*f[v[i]]-N)); }}intMain () {inti,x,y,z; memset (Point,-1,sizeof(point)); Memset (Next,-1,sizeof(next)); memset (V,0,sizeof(v)); Memset (P,0,sizeof(p)); Memset (c,0,sizeof(c)); Memset (F,0,sizeof(0)); scanf ("%d\n",&N); for(i=1; i<n;++i) {scanf ("%d%d%d\n",&x,&y,&z); Insect (x, y, z); Insect (y,x,z); }p[1]=1;d FS (1); printf ("%lld\n", sum); return 0;}View Code
BFS Version AC:
#include <queue>#include<cstdio>#include<cstring>#include<algorithm>using namespacestd;intn,point[1000003],next[2000003],v[2000003],c[2000003],cnt=0, f[1000003],s[1000003],fa[1000003];inttable[1000003],num=0, du[1000003];BOOLp[1000003];Long Longsum=0;voidInsect (intXintYintZ) {next[cnt]=point[x];p oint[x]=cnt;v[cnt]=y;c[cnt]=z;cnt++;}voidDfsintx) { intnow,i,tmp=0; Queue<int>Q; for(i=1; i<=n;++i) {if(du[i]==1) Q.push (i), F[i]=1; F[i]=1; } while(!Q.empty ()) { Now=q.front (); Q.pop (); p[now]=1; tmp=Now ; for(i=point[now];i!=-1; i=Next[i])if(p[v[i]]==0) {F[v[i]]+=F[now]; Du[v[i]]--; if(du[v[i]]==1) Q.push (V[i]); }} memset (P,0,sizeof(p)); P[TMP]=1; Q.push (TMP); while(!Q.empty ()) { Now=Q.front (); Q.pop (); for(i=point[now];i!=-1; i=Next[i])if(p[v[i]]==0) {P[v[i]]=1; Sum+ = (1ll*c[i]*abs (2*f[v[i]]-N)); Q.push (V[i]); }} printf ("%lld\n", sum);}intMain () {inti,x,y,z; memset (Point,-1,sizeof(point)); Memset (Next,-1,sizeof(next)); Memset (Du,0,sizeof(du)); memset (V,0,sizeof(v)); Memset (P,0,sizeof(p)); Memset (c,0,sizeof(c)); Memset (F,0,sizeof(0)); scanf ("%d\n",&N); for(i=1; i<n;++i) {scanf ("%d%d%d\n", &x,&y,&z); du[x]++; du[y]++; Insect (x, y, z); Insect (y,x,z); }dfs (1); return 0;}
Bzoj 2435 Road Construction NOI2011 tree DP