LCT板子
#include <bits/stdc++.h> const int MAXN=1e5+10; #define ll long long using namespace std; int ch[MAXN][2],res[MAXN],pre[MAXN];bool rt[MAXN]; ll size1[MAXN],size[MAXN];int st[MAXN],tp; typedef struct node{ int u,v;ll vul; }node; node d[MAXN]; ll readll(){ ll x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } int readint(){ int x=0,f=1;char ch=getchar(); while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} while(isdigit(ch))x=x*10+ch-'0',ch=getchar(); return f*x; } void update_res(int r){ if(!r) return ; swap(ch[r][0],ch[r][1]); res[r]^=1; } void push(int x){ if(res[x]){ update_res(ch[x][0]); update_res(ch[x][1]); res[x]^=1; } } void up(int x){ size[x]=size[ch[x][0]]+size[ch[x][1]]+size1[x]+1; } bool pd(int x){ return ch[pre[x]][0]!=x&&ch[pre[x]][1]!=x; } void P(int x){ int i;st[++tp]=x; for(i=x;!pd(i);i=pre[i]) st[++tp]=pre[i]; for(;tp;tp--) push(st[tp]); } void rotate(int x,int kind){ int y=pre[x]; ch[y][!kind]=ch[x][kind];pre[ch[x][kind]]=y; if(rt[y]) rt[x]=1,rt[y]=0; else ch[pre[y]][ch[pre[y]][1]==y]=x; pre[x]=pre[y];ch[x][kind]=y;pre[y]=x; up(y); } void splay(int x){ P(x); while(!rt[x]){ if(rt[pre[x]]) rotate(x,ch[pre[x]][0]==x); else{ int y=pre[x];int kind=ch[pre[y]][0]==y; if(ch[y][kind]==x) rotate(x,!kind),rotate(x,kind); else rotate(y,kind),rotate(x,kind); } } up(x); } void access(int x){ int y=0; while(x){ splay(x); if(ch[x][1]) rt[ch[x][1]]=1,size1[x]+=size[ch[x][1]],pre[ch[x][1]]=x; if(y) rt[y]=0,size1[x]-=size[y];ch[x][1]=y;up(x); y=x;x=pre[x]; } } void mroot(int u){ access(u);splay(u);update_res(u); } void Link(int u,int v){ mroot(u);mroot(v); pre[u]=v;size1[v]+=size[u];size[v]+=size[u]; } ll querty(int u,int v,ll vul){ mroot(u);access(v);splay(v); ll t=1ll*size[u]*(size[v]-size[u])*vul; pre[v]=pre[u]=0;rt[v]=rt[u]=1;ch[v][0]=0; up(u);up(v); return t; } void newnode(int v){ pre[v]=size1[v]=ch[v][0]=ch[v][1]=res[v]=0;rt[v]=1;size[v]=1; } bool cmp1(node aa,node bb){ return aa.vul>bb.vul; } bool cmp2(node aa,node bb){ return aa.vul<bb.vul; } int main(){ int n; while(scanf("%d",&n)!=EOF){ // inte(); for(int i=1;i<n;i++) d[i].u=readint(),d[i].v=readint(),d[i].vul=readint(); for(int i=1;i<=n;i++) newnode(i); for(int i=1;i<n;i++) Link(d[i].u,d[i].v); ll sum1=0; sort(d+1,d+n,cmp1); for(int i=1;i<n;i++) sum1+=querty(d[i].u,d[i].v,d[i].vul); //inte(); for(int i=1;i<=n;i++) newnode(i); for(int i=1;i<n;i++) Link(d[i].u,d[i].v); sort(d+1,d+n,cmp2); for(int i=1;i<n;i++) sum1-=querty(d[i].u,d[i].v,d[i].vul); printf("%lld\n",sum1); } return 0; }