在 W 星球上有 nn 个国家。为了各自国家的经济发展,他们决定在各个国家之间建设双向道路使得国家之间连通。但是每个国家的国王都很吝啬,他们只愿意修建恰好 n - 1n−1 条双向道路。
每条道路的修建都要付出一定的费用,这个费用等于道路长度乘以道路两端的国家个数之差的绝对值。例如,在下图中,虚线所示道路两端分别有 22 个、44 个国家,如果该道路长度为 11,则费用为 1 \times \lvert 2 - 4 \rvert =21×∣2−4∣=2。图中圆圈里的数字表示国家的编号。
由于国家的数量十分庞大,道路的建造方案有很多种,同时每种方案的修建费用难以用人工计算,国王们决定找人设计一个软件,对于给定的建造方案,计算出所需要的费用。请你帮助国王们设计一个这样的软件。
输入格式
输入的第一行包含一个整数 nn,表示 W 星球上的国家的数量,国家从 11 到 nn 编号。
接下来 n - 1n−1 行描述道路建设情况,其中第 ii 行包含三个整数 a_iai、b_ibi 和 c_ici,表示第 ii 条双向道路修建在 a_iai 与 b_ibi 两个国家之间,长度为 c_ici。
输出格式
输出一个整数,表示修建所有道路所需要的总费用。
数据范围和约定
对于所有数据,保证 1 \le a_i, b_i \le n, 0 \le c_i \le 10^61≤ai,bi≤n,0≤ci≤106.
测试点编号 | n=n= |
---|---|
1 | 22 |
2 | 1010 |
3 | 100100 |
4 | 200200 |
5 | 500500 |
6 | 600600 |
7 | 800800 |
8 | 10001000 |
9 | 10,00010,000 |
10 | 20,00020,000 |
11 | 50,00050,000 |
12 | 60,00060,000 |
13 | 80,00080,000 |
14 | 100,000100,000 |
15 | 600,000600,000 |
16 | 700,000700,000 |
17 | 800,000800,000 |
18 | 900,000900,000 |
19 | 1,000,0001,000,000 |
20 | 1,000,0001,000,000 |
Sample Input
6 1 2 1 1 3 1 1 4 2 6 3 1 5 2 1
Sample Output
20
#include <iostream>
#include <cmath>
using namespace std;
const int MAXN = 1e6+10;
struct info{
int to,nt,w;
};
info node[2*MAXN];
typedef long long ll;
ll size[MAXN],ans;
int cnt,n,pre[MAXN];
void add(int x,int y,int z)
{
cnt++;
node[cnt].to = y;
node[cnt].w = z;
node[cnt].nt = pre[x];
pre[x] = cnt;
}
void dfs(int x,int fa)
{
size[x] = 1;
for(int i = pre[x];i;i = node[i].nt){
int to = node[i].to;
if(to == fa)
continue; //防止往回搜索
dfs(to,x); //搜索子结点
size[x] += size[to];
ans += node[i].w * abs(2*size[to] - n);
}
}
int main()
{
scanf("%d",&n);
for(int i = 1;i < n;i++){
int x,y,z;
scanf("%d %d %d",&x,&y,&z);
add(x,y,z);
add(y,x,z);
}
dfs(1,0);
printf("%lld",ans);
return 0;
}