正题
题目链接:https://www.luogu.org/problem/P2052
题目大意
一棵树,一条边的价值是长度乘上两端点的数量差。求所有边的边权之和。
解题思路
统计子树大小就可以知道两端的数量差了。
c o d e code code
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
const ll N=1e6+10;
struct node{
ll to,next,w;
}a[2*N];
ll n,ans,tot=1,ls[N],siz[N],dep[N];
void addl(ll x,ll y,ll w)
{
a[++tot].to=y;
a[tot].next=ls[x];
a[tot].w=w;
ls[x]=tot;
}
void dfs(ll x,ll fa)
{
siz[x]=1;dep[x]=dep[fa]+1;
for(ll i=ls[x];i;i=a[i].next)
{
ll y=a[i].to;
if(y==fa) continue;
dfs(y,x);
siz[x]+=siz[y];
}
}
int main()
{
scanf("%lld",&n);
for(ll i=1;i<n;i++){
ll x,y,w;
scanf("%lld%lld%lld",&x,&y,&w);
addl(x,y,w);addl(y,x,w);
}
dfs(1,1);
for(ll i=2;i<=tot;i+=2){
ll x;
if(dep[a[i].to]>dep[a[i^1].to]) x=a[i].to;
else x=a[i^1].to;
ans+=abs(n-2*siz[x])*a[i].w;
}
printf("%lld",ans);
}