[luogu2052 NOI2011] 道路修建 (树形dp)

传送门

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

1≤ai, bi≤n

0≤ci≤10^6

2≤n≤10^6

Solution

不能再水的树形dp直接计算每条边的贡献

Code

//By Menteur_Hxy
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define F(i,a,b) for(register int i=(a);i<=(b);i++)
#define E(i,u) for(register int i=head[u];i;i=nxt[i])
using namespace std;
typedef long long LL;

int read() {
	int x=0,f=1; char c=getchar();
	while(!isdigit(c)) {if(c=='-')f=-f; c=getchar();}
	while(isdigit(c)) x=(x<<1)+(x<<3)+c-48,c=getchar();
	return x*f;
}

const int N=1000010;
int n,cnt;
int nxt[N<<1],to[N<<1],w[N<<1],head[N],siz[N];
long long ans;

void dfs(int u,int pre) {
	siz[u]=1;
	E(i,u) { int v=to[i];
		if(v==pre) continue;
		dfs(v,u);
		ans+=(LL)abs(n-siz[v]*2)*w[i];
		siz[u]+=siz[v];		
	}
}
 
#define add(a,b,c) nxt[++cnt]=head[a],to[cnt]=b,w[cnt]=c,head[a]=cnt
#define ins(a,b,c) add(a,b,c),add(b,a,c)
int main() {
	n=read();
	F(i,1,n-1) {
		int a=read(),b=read(),c=read();
		ins(a,b,c);
	}
	dfs(1,0);
	printf("%lld",ans);
	return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。 博主:https://www.cnblogs.com/Menteur-Hxy/
原文地址:https://www.cnblogs.com/Menteur-Hxy/p/9347899.html