Give a tree (directly to the tree, not to survive the graph !), Evaluate the Edge Weight * sum of the points on both sides
BFS water pass
In fact, DFS can also be used... The system Stack may be somewhat inadequate. We can use embedded assembly to manually open a large system stack. For details, see the code.
This reading optimization can optimize around 4 s
#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#define stack_size (20001000)#define M 1001001using namespace std;typedef long long ll;struct abcd{ int to,f,next;}table[M<<1];int head[M],tot;int n,fa[M],f[M],siz[M],q[M],r,h;ll ans;int stack[stack_size],bak;void DFS(int x){ int i; siz[x]=1; for(i=head[x];i;i=table[i].next) { if(table[i].to==fa[x]) continue; fa[table[i].to]=x; f[table[i].to]=table[i].f; DFS(table[i].to); siz[x]+=siz[table[i].to]; } ans+=(ll)abs(siz[x]+siz[x]-n)*f[x];}void CallDFS() { __asm__ __volatile__ ( "mov %%esp,%0\n" "mov %1,%%esp\n" :"=g"(bak) :"g"(stack+stack_size-1) : ); DFS(1); __asm__ __volatile__ ( "mov %0,%%esp\n" : :"g"(bak) : ); } inline int getc() { static const int L = 1 << 15; static char buf[L], *S = buf, *T = buf; if (S == T) { T = (S = buf) + fread(buf, 1, L, stdin); if (S == T) return EOF; } return *S++;}inline int getint() { int c; while(!isdigit(c = getc()) && c != '-'); bool sign = c == '-'; int tmp = sign ? 0 : c - '0'; while(isdigit(c = getc())) tmp = (tmp << 1) + (tmp << 3) + c - '0'; return sign ? -tmp : tmp;}void Add(int x,int y,int z){ table[++tot].to=y; table[tot].f=z; table[tot].next=head[x]; head[x]=tot;}int main(){ int i,x,y,z; cin>>n; for(i=1;i<n;i++) { x=getint(); y=getint(); z=getint(); Add(x,y,z); Add(y,x,z); } CallDFS(); cout<<ans<<endl;}
Bzoj 2435 noi2011 road construction BFS/DFS