num[x]表示x到达叶子最远路径。
每个子节点对答案的贡献是num[x] - (num[t] + edge[i].val)
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
int n, ss, hea[500005], cnt, uu, vv, ww;
ll num[500005], ans;
struct Edge{
int too, nxt, val;
}edge[1000005];
void add_edge(int fro, int too, int val){
edge[++cnt].nxt = hea[fro];
edge[cnt].too = too;
edge[cnt].val = val;
hea[fro] = cnt;
}
void dfs(int x, int f){
for(int i=hea[x]; i; i=edge[i].nxt){
int t=edge[i].too;
if(t!=f){
dfs(t, x);
num[x] = max(num[x], num[t]+edge[i].val);
}
}
for(int i=hea[x]; i; i=edge[i].nxt){
int t=edge[i].too;
if(t!=f)
ans += num[x] - (num[t] + edge[i].val);
}
}
int main(){
cin>>n>>ss;
for(int i=1; i<n; i++){
scanf("%d %d %d", &uu, &vv, &ww);
add_edge(uu, vv, ww);
add_edge(vv, uu, ww);
}
dfs(ss, 0);
cout<<ans<<endl;
return 0;
}