P2052 [NOI2011] road construction
In fact, this problem can put things inside dfs finish work, (I also began to seek out a handful) ......
The contribution of one side is the son of the size and n-siz [v] Take the upper right;
#include<cmath> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn=1e6+10; typedef long long ll; int pre[maxn*2],last[maxn],other[maxn*2],len[maxn*2],l; void add(int x,int y,int z) { l++; pre[l]=last[x]; last[x]=l; other[l]=y; len[l]=z; } int n; int father[maxn]; int siz[maxn]; ll ans; void dfs(int x,int fa) { siz[x]=1; for(int p=last[x];p;p=pre[p]) { int v=other[p]; if(v==fa) continue; dfs(v,x); ans+=(ll)abs(n-2*siz[v])*len[p]; siz[x]+=siz[v]; } } int main() { scanf("%d",&n); for(int i=1;i<n;i++) { int a,b,c; scanf("%d%d%d",&a,&b,&c); add(a,b,c); add(b,a,c); } dfs(1,1); printf("%lld",ans); return 0; }