CodeForces - 743D Chloe and pleasant prizes 树形DP

题意:给你一棵树,每个节点有个值,同时选择两棵子树,不能有重叠,求两颗子树所能得到的最大值。

在树上DP就好了 dp[i]表示i节点为根的子树中能选取到的最大值 

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define maxn 200005
#define oo 2000000005
using namespace std;
typedef long long ll;
struct node{
	int to,nxt;
}ed[maxn<<1];
int head[maxn],cnt;
void addedge(int u,int v){
	ed[cnt].to=v,ed[cnt].nxt=head[u],head[u]=cnt++;
}
ll vl[maxn],dp[maxn];
bool vis[maxn];
ll ans;
void dfs(int u){
	dp[u]=-oo;
	vis[u]=1;
	for(int i=head[u];~i;i=ed[i].nxt){
		int v=ed[i].to;
		if(vis[v])continue;
		dfs(v);
		vl[u]+=vl[v];
		if(dp[u]>-oo)ans=max(ans,dp[u]+dp[v]);
		dp[u]=max(dp[u],dp[v]);
		
	}
	dp[u]=max(dp[u],vl[u]);
}
int main()
{
	ans=-oo;
	memset(head,-1,sizeof(head));
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%lld",&vl[i]);
	for(int i=1;i<n;i++){
		int a,b;
		scanf("%d%d",&a,&b);
		addedge(a,b);
		addedge(b,a);
	}
	dfs(1);
	if(ans==-oo)printf("Impossible\n");
	else printf("%lld\n",ans);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值