解题思路
这题怕是noi的耻辱,理解题意有点困难,是建好树以后算,并不是决策。理解题意后就十分简单了,一遍dfs。
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#define LL long long
using namespace std;
const int MAXN=1e6+5;
inline int rd(){
int x=0,f=1;char ch=getchar();
while(!isdigit(ch)) {f=ch=='-'?0:1;ch=getchar();}
while(isdigit(ch)) {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
return f?x:-x;
}
int n,head[MAXN],cnt,to[MAXN<<1],nxt[MAXN<<1],val[MAXN<<1];
int siz[MAXN];
LL ans;
inline void add(int bg,int ed,int w){
to[++cnt]=ed,nxt[cnt]=head[bg],val[cnt]=w,head[bg]=cnt;
}
void dfs(int x,int pre){
siz[x]=1;
for(register int i=head[x];i;i=nxt[i]){
int u=to[i];if(u==pre) continue;
dfs(u,x);
siz[x]+=siz[u];
ans+=(LL)val[i]*abs(n-siz[u]-siz[u]);
}
}
int main(){
n=rd();int x,y,z;
for(register int i=1;i<n;i++){
x=rd(),y=rd(),z=rd();
add(x,y,z),add(y,x,z);
}
dfs(1,0);cout<<ans<<endl;
return 0;
}