聚会[树形DP]

聚会  

 给你 n 个点,任意两点之间有唯一路径可到达 
 每个点有一个点权 Ci 
 每条边有个边权 Wi 

问:找出一个点作为聚会点,使得所有其他点到该点代价总和最小,代
价=点权*路径。如:i 作为集合点,点 x 的代价为 Cx*Len(x,i) ,Len(x,i)表示 x 到 i 的距离。 

【输入样例】 
5

1 1 0 0 2

1 3 1

2 3 2

3 4 3

4 5 3

【输出样例】 
15 
  
【数据规模】 
30%数据:N<=30 
100%数据:N<=100000,0<=Ci,W<=1000

分析

树形DP

void Dfs(LL cur,LL fa)
{
	for(LL i=first[cur];i;i=next[i]){
		LL t=to[i];
		if(t==fa) continue;
		f[t]=f[cur]+(sum-num[t])*w[i]-num[t]*w[i];
		ans=min(ans,f[t]);
		Dfs(t,cur);
	}
}

num[t]为以t为根的节点的Ci和 sum为全部的Ci和

sum,num,f[1]均可在第一遍dfs取出

一般的树形DP是子节点推父节点,而这道不同

我们要知道状态转移需要什么东西,以及状态如何变化 

树上的问题往往伴随容斥原理出现

#include<bits/stdc++.h>
#define N 100005
#define LL long long
using namespace std;
LL first[N],next[N*2],to[N*2],w[N*2],tot;
LL n,c[N],sum,ans=1e17;
LL f[N],num[N],dis[N];
LL read()
{
	LL cnt=0;
	char ch=0;
	while(!isdigit(ch)) ch=getchar();
	while(isdigit(ch)){
		cnt=(cnt<<1)+(cnt<<3)+(ch-'0');
		ch=getchar();
	}
	return cnt;
}
void add(LL x,LL y,LL z)
{
	next[++tot]=first[x];
	first[x]=tot;
	to[tot]=y;
	w[tot]=z;
}
void dfs(LL cur,LL fa)
{
	for(LL i=first[cur];i;i=next[i]){
		LL t=to[i];
		if(t==fa) continue;
		dis[t]=dis[cur]+w[i];
		f[1]+=(LL)dis[t]*c[t];
	    dfs(t,cur);
	    num[cur]+=num[t];
	}
}
void Dfs(LL cur,LL fa)
{
	for(LL i=first[cur];i;i=next[i]){
		LL t=to[i];
		if(t==fa) continue;
		f[t]=f[cur]+(sum-num[t])*w[i]-num[t]*w[i];
		ans=min(ans,f[t]);
		Dfs(t,cur);
	}
}
int main()
{
    n=read();
	for(LL i=1;i<=n;i++) 
	  c[i]=read(),num[i]=c[i],sum+=c[i];
	for(LL i=1;i<=n-1;i++){
		LL x=read(),y=read(),z=read();
		add(x,y,z),add(y,x,z);
	}
	dfs(1,0);
	Dfs(1,0);
	cout<<min(ans,f[1]);
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FSYo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值