#include <stdio.h>
int main()
{
puts("转载请注明出处[vmurder]谢谢");
puts("网址:blog.csdn.net/vmurder/article/details/44655619");
}
树形DP记录size。然后每个子树回来是边的两边数量是
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define N 1001000
#define inf 0x3f3f3f3f
using namespace std;
struct Eli
{
int v,len,next;
}e[N<<1];
int head[N],cnt;
inline void add(int u,int v,int len)
{
e[++cnt].v=v;
e[cnt].len=len;
e[cnt].next=head[u];
head[u]=cnt;
}
int n;
long long ans;
int dfs(int x,int p)
{
int i,v,size=1;
for(i=head[x];i;i=e[i].next)
{
v=e[i].v;
if(v==p)continue;
int t=dfs(v,x);size+=t;
ans+=(long long)abs((n-t)-t)*e[i].len;
}
return size;
}
int main()
{
freopen("test.in","r",stdin);
int i,j,k;
int a,b,c;
scanf("%d",&n);
for(i=1;i<n;i++)
{
scanf("%d%d%d",&a,&b,&c);
add(a,b,c),add(b,a,c);
}
dfs(1,0);
cout<<ans<<endl;
}
原文:http://blog.csdn.net/vmurder/article/details/44655619