Problem:
Score : 1100 points

Problem Statement

There is a tree with N vertices, numbered 1 through N.
The i-th edge in this tree connects Vertices A_i and B_i and has a length of C_i.

Joisino created a complete graph with N vertices.
The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u and v in the tree above.

Joisino would like to know the length of the longest Hamiltonian path (see Notes) in this complete graph.
Find the length of that path.

Notes

A Hamiltonian path in a graph is a path in the graph that visits each vertex exactly once.

Constraints

2 \leq N \leq 10^5

1 \leq A_i < B_i \leq N

The given graph is a tree.

1 \leq C_i \leq 10^8

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1 C_1
A_2 B_2 C_2
:
A_{N-1} B_{N-1} C_{N-1}

Output

Print the length of the longest Hamiltonian path in the complete graph created by Joisino.

Sample Input 1

5
1 2 5
3 4 7
2 3 3
2 5 2

Sample Output 1

38

The length of the Hamiltonian path 5 → 3 → 1 → 4 → 2 is 5+8+15+10=38. Since there is no Hamiltonian path with length 39 or greater in the graph, the answer is 38.

Sample Input 2

8
2 8 8
1 5 1
4 8 2
2 5 4
3 8 6
6 8 9
2 7 12

Sample Output 2

132

Solution in C++14 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
using namespace std;
typedef long long LL;
const int N=100005;
int n,sz[N],f[N],q[N];LL ans;
int pp,lnk[N],nxt[N*2],to[N*2],w[N*2];
void ae(int k1,int k2,int k3){to[++pp]=k2,w[pp]=k3,nxt[pp]=lnk[k1],lnk[k1]=pp;} 
void dfs(int k1,int k2){
	sz[k1]=1;
	for(int i=lnk[k1];i;i=nxt[i])if(to[i]!=k2){
		dfs(to[i],k1);
		sz[k1]+=sz[to[i]];
		if(sz[to[i]]>f[k1])f[k1]=sz[to[i]];
		ans+=2LL*min(sz[to[i]],n-sz[to[i]])*w[i];
	}
	if(n-sz[k1]>f[k1])f[k1]=n-sz[k1];
}
int main(){
	scanf("%d",&n);
	rep(i,2,n){int k1,k2,k3;scanf("%d%d%d",&k1,&k2,&k3),ae(k1,k2,k3),ae(k2,k1,k3);}
	dfs(1,0);
	q[*q=1]=1;
	rep(i,2,n){
		if(f[i]<f[q[*q]])q[*q=1]=i;
		else if(f[i]==f[q[*q]])q[++*q]=i;
	}
	if(*q==1){
		LL now=0X7FFFFFFFFFFFFFFFLL;
		for(int i=lnk[q[1]];i;i=nxt[i]){
			if(sz[q[1]]<sz[to[i]]){
				now=min(now,1LL*(n-sz[q[1]])*w[i]);
			}else{
				now=min(now,1LL*sz[to[i]]*w[i]);
			}
		}
//		printf(">>> %lld %lld\n",ans,now);
		printf("%lld\n",ans-now);
	}else{
//		printf("q:");
//		rep(i,1,*q)printf("%d ",q[i]);puts("");
		assert(*q==2);
		for(int i=lnk[q[1]];i;i=nxt[i])if(to[i]==q[2]){
			printf("%lld\n",ans-1LL*(n/2)*w[i]);
			return 0;
		}
	}
	return 0;
}