Describe:最小生成树加权
code:
#include<bits/stdc++.h>
#define INF 214748364
#define eps 1e-9
#define rep1(a,b) for(register long long i=(a);i<=(b);i++)
#define rep2(a,b) for(register long long j=(a);j<=(b);j++)
using namespace std;
struct JXCjulao{
long long l,r,w;
}dis[100005];
long long n,ans,fa[100005],sum[100005];
bool cmp(const JXCjulao a,const JXCjulao b){return a.w<b.w;}
inline long long gf(long long t){return fa[t]==t?t:(fa[t]=gf(fa[t]));}
inline long long read(){
long long ret=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9') {if (ch=='-') f=-f;ch=getchar();}
while (ch>='0'&&ch<='9') ret=ret*10+ch-'0',ch=getchar();
return ret*f;
}
inline double read2(){
double X=0,Y=1.0;long long w=0;char ch=0;
while(!isdigit(ch)){w|=ch=='-';ch=getchar();}
while(isdigit(ch))X=X*10+(ch^48),ch=getchar();
ch=getchar();
while(isdigit(ch)) X+=(Y/=10)*(ch^48),ch=getchar();
return w?-X:X;
}
inline void write(long long x){
if(x<0){putchar('-');write(-x);return;}
if(x/10) write(x/10);putchar(x%10+'0');
}
int main(){
//freopen("tree.in","r",stdin);
//freopen("tree.out","w",stdout);
n=read();
for(register long long i=1;i<=n;i++)fa[i]=i,sum[i]=1;
for(register long long i=1;i<n;i++)
dis[i].l=read(),dis[i].r=read(),dis[i].w=read();
sort(dis+1,dis+n,cmp);
for(register long long i=1;i<n;i++){ //Kruskal
long long fx=gf(dis[i].l),fy=gf(dis[i].r);
if(fx!=fy){
ans+=sum[fx]*sum[fy]*(dis[i].w+1)-1; //求出左边费用加右边费用,加一是为了保证最小生成树的唯一性
fa[fx]=fy;sum[fy]+=sum[fx];
}
}
write(ans);puts("");
return 0;
}