您的位置:首页 > 其它

CodeForces - 743D Chloe and pleasant prizes 树形DP

2016-12-15 14:54 411 查看
题意:给你一棵树,每个节点有个值,同时选择两棵子树,不能有重叠,求两颗子树所能得到的最大值。

在树上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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: