传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=2435
说好的卡爆栈呢
Code;
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
struct edge{int v,w;};
vector<edge>G[maxn];
typedef long long LL;
LL sum=0,ans=0;
int size[maxn],vis[maxn],n;
void dfs(int u){
size[u]=1;edge e;
for(int i=0;i<G[u].size();i++)
if(!vis[(e=G[u][i]).v]){
vis[e.v]=1;
dfs(e.v);
size[u]+=size[e.v];
ans+=(LL)abs(n-size[e.v]-size[e.v])*e.w;
}
}
int getint(){
int res=0;char c=getchar();
while(!isdigit(c))c=getchar();
while(isdigit(c))res=res*10+c-'0',c=getchar();
return res;
}
int main(){
scanf("%d",&n);
for(int i=1;i<n;i++){
int u=getint(),v=getint(),w=getint();
G[u].push_back((edge){v,w});
G[v].push_back((edge){u,w});
}vis[1]=1;dfs(1);
cout<<ans<<endl;
return 0;
}