道路修建
問題描述
現在在LJY星球上有
LJY爲了使各個國家的經濟發展,決定在各個國家之間建設雙向道路使得國家之間連通。
但是LJY很吝嗇,只願意修建恰好
每條道路的修建都要付出一定的費用,這個費用等於道路長度乘以道路兩端的國家個數之差的絕對值。
例如,在下圖中,虛線所示道路兩端分別有
圖中圓圈裏的數字表示國家的編號。
由於國家的數量十分龐大,道路的建造方案有很多種,同時每種方案的修建費用難以用人工計算,LJY決定找人設計一個軟件,對於給定的建造方案,計算出所需要的費用。
請你幫助LJY設計一個這樣的軟件。
輸入
輸入文件名爲Road.in。
輸入第一行爲一個正整數
下接
輸出
輸出文件名爲Road.txt。
輸出一行一個正整數,爲修建所有道路的總費用。
輸入樣例
6
1 2 1
1 3 1
1 4 2
6 3 1
5 2 1
輸出樣例
20
數據範圍
對於
對於
對於
不允許開開關。
Solution
首先無向圖轉有向圖。
用
則
於是
Code
#include <iostream>
#include <cstdio>
#include <cstring>
#define LL long long
#define abs(x) ((x)>0?(x):(-1)*(x))
using namespace std;
int n,cnt;
LL ans;
int head[1000010],nxt[2000010],data[2000010],weight[2000010];
int f[1000010];
bool vis[1000010];
void add(int x,int y,int z){
nxt[cnt]=head[x];data[cnt]=y;weight[cnt]=z;head[x]=cnt++;
nxt[cnt]=head[y];data[cnt]=x;weight[cnt]=z;head[y]=cnt++;
}
void dfs(int now){
f[now]=vis[now]=1;
for(int i=head[now];i!=-1;i=nxt[i])if(!vis[data[i]]){
dfs(data[i]);
ans+=(LL)abs(2*(f[data[i]])-n)*weight[i];
f[now]+=f[data[i]];
}
}
inline void in(int &x){
x=0;char ch=getchar();
while(ch<'0'||ch>'9')ch=getchar();
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
}
int main(){
freopen("road.in","r",stdin);
freopen("road.out","w",stdout);
memset(head,-1,sizeof head);
scanf("%d",&n);
for(int i=1;i<n;i++){
int a,b,c;
in(a),in(b),in(c);
add(a,b,c);
}
dfs(1);
printf("%lld\n",ans);
return 0;
}