十年前的ZJOI真良心,n=1e6还O(n)。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define rep(i,j,k) for(i=j;i<=k;++i)
#define per(i,j,k) for(i=j;i>=k;--i)
#define sqr(x) ((x)*(x))
#define G getchar()
#define LL long long
#define pil pair<int,LL>
#define mkp make_pair
#define X first
#define Y second
#define N 1000005
#define NN 10000000
#define inf 1061109567
#define eps 0.00001
int n,rt,tot,he[N],ne[N<<1],to[N<<1];LL W[N<<1],ans;
int read(){
int x=0;char ch=G;
while(ch<48||ch>57)ch=G;
for(;ch>47&&ch<58;ch=G)x=x*10+ch-48;
return x;
}
void add(int x,int y,LL z){
to[++tot]=y;W[tot]=z;ne[tot]=he[x];he[x]=tot;
}
void DFS(int x,int e){
int i,y,cnt=0;LL Max=0,sum=0;
for(i=he[x];i;i=ne[i])if(i!=e){
DFS(y=to[i],i^1);Max=max(Max,W[i]);sum+=W[i];++cnt;
}
ans+=Max*cnt-sum;W[e]=W[e^1]=W[e]+Max;
}
int main(){
int i,x,y;LL z;
n=read();rt=read();tot=1;
rep(i,2,n){
x=read();y=read();z=read();
add(x,y,z);add(y,x,z);
}
DFS(rt,0);printf("%lld\n",ans);
return 0;
}