1 #include<iostream>
2 #include<cstring>
3 #include<cstdio>
4 #include<cmath>
5 #define ll long long
6 using namespace std;
7 struct node
8 {
9 int pre;
10 int to;
11 int w;
12 }N[2000040];
13 int nedge=0;
14 int pre[1000020];
15 int n;
16 int used[1000020];
17 int s[1000020];
18 ll ans=0;
19 void add(int a,int b,int c)
20 {
21 nedge++;
22 N[nedge].to=b;
23 N[nedge].w=c;
24 N[nedge].pre=pre[a];
25 pre[a]=nedge;
26 }
27 int ab(int x)
28 {
29 if(x<0)
30 return -x;
31 return x;
32 }
33 void dfs(int xx)
34 {
35 s[xx]=1;
36 for(int i=pre[xx];i;i=N[i].pre)
37 {
38 if(!used[N[i].to])
39 {
40 used[N[i].to]=1;
41 dfs(N[i].to);
42 s[xx]+=s[N[i].to];
43 ans=ans+(ll)N[i].w*ab(s[N[i].to]-(n-s[N[i].to]));
44 //cout<<"!!!"<<N[i].w<<" "<<s[xx]<<" "<<n-s[xx]<<endl;
45 }
46 }
47 }
48 int aa,bb,cc;
49 int main()
50 {
51 while(scanf("%d",&n)!=EOF)
52 {
53 memset(used,0,sizeof(used));
54 nedge=0;
55 ans=0;
56 memset(pre,0,sizeof(pre));
57 memset(s,0,sizeof(s));
58 for(int i=1;i<n;i++)
59 {
60 scanf("%d %d %d",&aa,&bb,&cc);
61 add(aa,bb,cc);
62 add(bb,aa,cc);
63 }
64 used[1]=1;
65 dfs(1);
66 printf("%lld\n",ans);
67 }
68 return 0;
69 }