您的位置:首页 > 其它

BZOJ2435: [Noi2011]道路修建

2017-11-18 15:27 537 查看
Description

在 W 星球上有 n 个国家。为了各自国家的经济发展,他们决定在各个国家

之间建设双向道路使得国家之间连通。但是每个国家的国王都很吝啬,他们只愿

意修建恰好 n – 1条双向道路。 每条道路的修建都要付出一定的费用, 这个费用等于道路长度乘以道路两端的国家个数之差的绝对值。例如,在下图中,虚线所示道路两端分别有 2 个、4个国家,如果该道路长度为 1,则费用为1×|2 – 4|=2。图中圆圈里的数字表示国家的编号。



由于国家的数量十分庞大,道路的建造方案有很多种,同时每种方案的修建

费用难以用人工计算,国王们决定找人设计一个软件,对于给定的建造方案,计

算出所需要的费用。请你帮助国王们设计一个这样的软件。

Input

输入的第一行包含一个整数n,表示 W 星球上的国家的数量,国家从 1到n

编号。接下来 n – 1行描述道路建设情况,其中第 i 行包含三个整数ai、bi和ci,表

示第i 条双向道路修建在 ai与bi两个国家之间,长度为ci。

Output

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

Sample Input

6

1 2 1

1 3 1

1 4 2

6 3 1

5 2 1

Sample Output

20

HINT

n = 1,000,000 1≤ai, bi≤n

0 ≤ci≤ 10^6

题目传送门

刚拿到题的时候,一脸凝重,已经做好了死磕2小时的准备

2分钟后…这是noi的题?不是dfs吗?别骗我啊

不对啊,他每条边都一定要用啊,要不然不联通

试试吧…

然后水掉了

垃圾题目,毁我青春

代码如下:

#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
int n;
typedef long long ll;
struct node{
int x,y,next;
ll d;
}a[2100000];int len,last[2100000];
void ins(int x,int y,ll d)
{
len++;
a[len].x=x;a[len].y=y;a[len].d=d;
a[len].next=last[x];last[x]=len;
}
ll ans;
int tot[2100000];
void dfs(int x,int fa)
{
tot[x]=1;
for(int k=last[x];k;k=a[k].next)
{
int y=a[k].y;
if(y!=fa)
{
dfs(y,x);
tot[x]+=tot[y];
ans+=ll(a[k].d*abs(n-tot[y]-tot[y]));
}
}
}
int main()
{
scanf("%d",&n);
len=0;memset(last,0,sizeof(last));
for(int i=1;i<n;i++)
{
int x,y;ll d;
scanf("%d%d%lld",&x,&y,&d);
ins(x,y,d);ins(y,x,d);
}
ans=0;
dfs(1,0);
printf("%lld\n",ans);
return 0;
}


by_lmy
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: