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: Accepted)

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
vector<LL> edges[110000];
vector<LL> wgt[110000];
LL sz[110000];
LL ok[110000];

LL ans = 0;
LL medge = 1e9;
LL n;
LL t = -1;
void dfs(int a, int p){
	sz[a] = 1;
	ok[a] = 1;	
	for(int j = 0; j < edges[a].size(); j++){
		if(edges[a][j] == p) continue;
		dfs(edges[a][j],a);
		LL k = sz[edges[a][j]];
		ans += 2LL*min(k,n-k) * wgt[a][j];
		sz[a] += k;
		if(k > (n/2)){
			ok[a] = 0;
		}
		if(k*2 == n){
			medge = wgt[a][j];
		}
	}
	if(n-sz[a] > (n/2)) ok[a] = 0;
	if(ok[a]){
		t = a;
	}
}

int main(){
	cin >> n;
	for(int i = 1; i < n; i++){
		LL a, b, c;
		cin >> a >> b >> c;
		a--; b--;
		edges[a].push_back(b);
		edges[b].push_back(a);
		wgt[a].push_back(c);
		wgt[b].push_back(c);
	}
	ans = 0;
	dfs(0,-1);
	if(medge == 1e9 && t != -1){
		for(int j = 0; j < edges[t].size(); j++){
			medge = min(medge, wgt[t][j]);
		}
	}
	ans -= medge;
	cout << ans << endl;
}