0
点赞
收藏
分享

微信扫一扫

聚会[树形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]_树形dp

一般的树形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;
}

 


举报

相关推荐

树形 DP

树形DP.

树形dp总结

树形dp 笔记

树形DP练习

树形DP专题

Weight the Tree(树形dp)

题解 树形DP (一)

0 条评论