Chinese Postman Problem is a very famous hard problem in graph theory. The problem is to find a shortest closed path or circuit that visits every edge of a (connected) undirected graph. When the graph has an Eulerian Circuit (a closed walk that covers every edge once), that circuit is an optimal solution.
This problem is another version of Postman Problem. Assume there are n towns and n-1 roads, and there is a unique path between every pair of towns. There are n-1 postmen in every town, and each postman in one town regularly sends mails to one of the other n-1 towns respectively. Now, given the length of each road, you are asked to calculate the total length that all the postmen need to travel in order to send out the mails.
For example, there are six towns in the following picture. The 30 postmen should totally travel 56. The postmen in town 0 should travel 1, 2, 2, 2, 3 respectively, the postmen in town 1 should travel 1, 1, 1, 1, 2 respectively, the postmen in town 2 should travel 1, 1, 2, 2, 2 respectively, the postmen in town 3 should travel 1, 2, 3, 3, 3 respectively, the postmen in town 4 should travel 1, 2, 2, 2, 3 respectively, and the postmen in town 5 should travel 1, 2, 2, 2, 3 respectively. So the total distance is 56.
Input
The first line of the input contains an integer T(T≤20), indicating the number of test cases. Each case begins with one integer n(n≤100,000), the number of towns. In one case, each of the following n-1 lines describes the length of path between pair a and b, with the format a, b, c(1≤c≤1000), indicating that town a and town b are directly connected by a road of length c. Note that all the n towns are numbered from 0 to n-1.
Output
For each test case, print a line containing the test case number (beginning with 1) and the total sum of the length that all postmen should travel.
Sample Input
Sample Output
//
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=210000;
struct Node
{
int v,w;
int next;
};
int n;
Node G[maxn];
int p[maxn];
int l;
void init()
{
memset(p,-1,sizeof(p));
l=0;
}
void addedge(int u,int v,int w,int l)
{
G[l].v=v;
G[l].w=w;
G[l].next=p[u];
p[u]=l;
}
int son[maxn];
void calcSon(int u,int fath)
{
son[u]=1;
for(int i=p[u];i!=-1;i=G[i].next)
{
int v=G[i].v;
if(v==fath) continue;
calcSon(v,u);
son[u]+=son[v];
}
}
long long ans;
void dfs(int u,int fath)
{
for(int i=p[u];i!=-1;i=G[i].next)
{
int v=G[i].v,w=G[i].w;
if(v==fath) continue;
ans+=(long long)w*(n-son[v])*son[v];
dfs(v,u);
}
}
int main()
{
int ci,pl=1;scanf("%d",&ci);
while(ci--)
{
scanf("%d",&n);
init();
ans=0;
for(int i=0;i<n-1;i++)
{
int u,v,w;scanf("%d%d%d",&u,&v,&w);
addedge(u,v,w,l++);
addedge(v,u,w,l++);
}
calcSon(0,-1);
dfs(0,-1);
cout<<"Case "<<pl++<<": "<<ans*2<<endl;
}
return 0;
}