NOIp2011道路修建

题目描述

在 W 星球上有 n 个国家。为了各自国家的经济发展,他们决定在各个国家 之间建设双向道路使得国家之间连通。但是每个国家的国王都很吝啬,他们只愿 意修建恰好 n – 1 条双向道路。 每条道路的修建都要付出一定的费用,这个费用等于道路长度乘以道路两端 的国家个数之差的绝对值。例如,在下图中,虚线所示道路两端分别有 2 个、4 个国家,如果该道路长度为 1,则费用为 1×|2 – 4|=2。图中圆圈里的数字表示国 家的编号。 

由于国家的数量十分庞大,道路的建造方案有很多种,同时每种方案的修建 费用难以用人工计算,国王们决定找人设计一个软件,对于给定的建造方案,计 算出所需要的费用。请你帮助国王们设计一个这样的软件。

输入输出格式

输入格式:

输入的第一行包含一个整数 n,表示 W 星球上的国家的数量,国家从 1 到 n 编号。 接下来 n – 1 行描述道路建设情况,其中第 i 行包含三个整数 ai、bi和 ci,表 示第 i 条双向道路修建在 ai与 bi两个国家之间,长度为 ci。

输出格式:

输出一个整数,表示修建所有道路所需要的总费用。

输入输出样例

输入样例#1:
6
1 2 1
1 3 1
1 4 2
6 3 1
5 2 1
输出样例#1:
20

说明

1≤ai, bi≤n

0≤ci≤10^6

2≤n≤10^6

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn=1000000+5;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0'; ch=getchar();}
    return x*f;
}
int n,num; ll ans;
int head[maxn],son[maxn];
bool vis[maxn];
struct node
{
    int next,to,dist;
}e[maxn];
inline void add(int from,int to,int dist)
{
    e[++num].next=head[from];
    e[num].to=to;
    e[num].dist=dist;
    head[from]=num;
}
void dfs(int x)
{
    son[x]=1; vis[x]=1;
    for(int i=head[x];i;i=e[i].next)
    if(!vis[e[i].to])
    {
        dfs(e[i].to);
        son[x]+=son[e[i].to];
        ans+=(ll)abs((n-son[e[i].to]-1)-(son[e[i].to]-1))*(ll)e[i].dist;
    }
}
int main()
{
    n=read();
    for(int i=1;i<n;i++)
    {
        int x,y,z;
        x=read();y=read();z=read();
        add(x,y,z); add(y,x,z);
    }
    dfs(1);
    printf("%lld
",ans);
    return 0;
}
    
欢迎转载,转载请注明出处!
原文地址:https://www.cnblogs.com/huihao/p/7470277.html