bzoj2435,懒得复制,戳我戳我
Solution:
Code:
//It is coded by Ning_Mew on 5.13
#include<bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn=1e6+7;
int n;
LL ans=0;
int siz[maxn];
int head[maxn],cnt=0;
struct Edge{
int nxt,to,dis;
}edge[maxn*2];
void add(int from,int to,int dis){
edge[++cnt].nxt=head[from];edge[cnt].to=to;
edge[cnt].dis=dis;head[from]=cnt;
}
void dfs(int fa,int u){
siz[u]=1;
for(int i=head[u];i!=0;i=edge[i].nxt){
int v=edge[i].to;if(v==fa)continue;
dfs(u,v);
siz[u]+=siz[v];
ans+=abs(n-siz[v]-siz[v])*edge[i].dis;
}return;
}
int main(){
scanf("%d",&n);
for(int i=1;i<n;i++){
int x,y,z;scanf("%d%d%d",&x,&y,&z);
add(x,y,z);add(y,x,z);
}
dfs(1,1);
printf("%lld\n",ans);
return 0;
}