2435: [Noi2011]道路修建
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
【解题报告】
希望NOI多考考这种水题
代码如下:
/**************************************************************
Problem: 2435
User: onepointo
Language: C++
Result: Accepted
Time:7156 ms
Memory:94312 kb
****************************************************************/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<stack>
using namespace std;
#define N 1000010
#define LL long long
int n;LL ans;
int cnt,head[N],size[N];
struct Edge{int to,nxt;LL w;}e[N<<1];
void adde(int u,int v,LL w)
{
e[++cnt].to=v;e[cnt].w=w;
e[cnt].nxt=head[u];head[u]=cnt;
e[++cnt].to=u;e[cnt].w=w;
e[cnt].nxt=head[v];head[v]=cnt;
}
void dfs(int u,int fa)
{
size[u]=1;
for(int i=head[u];~i;i=e[i].nxt)
{
int v=e[i].to;
if(v==fa) continue;
dfs(v,u);
size[u]+=size[v];
ans+=e[i].w*(LL)abs(n-(size[v]<<1));
}
}
int main()
{
cnt=-1;ans=0;
memset(head,-1,sizeof(head));
scanf("%d",&n);
for(int i=1;i<n;++i)
{
int u,v;LL w;
scanf("%d%d%lld",&u,&v,&w);
adde(u,v,w);
}
dfs(1,1);
printf("%lld\n",ans);
return 0;
}