CF 533 B. Work Group 树形dp

题目链接


题意:

给出一棵树(n<=2e5),每个点有权值,要求选出权值和尽可能大的点集,使每个点都能有偶数个后代结点被选进去(可以为0)。


对于结点x,先处理子结点y1…yn

初始化 dp[x][0]=0,dp[x][1]=-inf;

dp[x][1]=max{ dp[x][0]+dp[yi][1],dp[x][1]+dp[yi][0] };
dp[x][0]=max{ dp[x][0]+dp[yi][0],dp[x][1]+dp[yi][1] };

再考虑是否选点x
dp[x][1]=max(dp[x][1],dp[x][0]+a[x])

这样dp[x][0]和dp[x][1]均为偶数方便了后续转移。


代码:

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
using namespace std;

#define all(x) (x).begin(), (x).end()
#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)
#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)
#define mes(a,x,s)  memset(a,x,(s)*sizeof a[0])
#define mem(a,x)  memset(a,x,sizeof a)
typedef long long ll;
typedef pair<int, int> pii;
const double inf =1e15;
const int maxn=2e5+0.5    ;
int n,a[maxn+10];

vector<int >G[maxn+10];
ll dp[maxn+5][2];
void update(ll & x,ll val)
{
    if(val>x)  x=val;
}
void dfs(int x)
{
    int siz=G[x].size();
    dp[x][0]=0;dp[x][1]=-inf;
    for0(i,siz)
    {
        int y=G[x][i];  dfs(y);
        ll ret0=dp[x][0],ret1=dp[x][1];
        update(dp[x][0], max(ret1+dp[y][1],ret0+dp[y][0]) );
        update(dp[x][1], max(ret1+dp[y][0],ret0+dp[y][1]) );
    }
    dp[x][1]=max(dp[x][1],dp[x][0]+a[x]);
}
int main()
{
   std::ios::sync_with_stdio(false);
   while(cin>>n)
   {
       for1(i,n) G[i].clear();
       int x;
       for1(i,n)
       {
           cin>>x>>a[i];
           if(~x)  G[x].push_back(i);
       }
       dfs(1);
       cout<<max(dp[1][0],dp[1][1])<<endl;
   }
   return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值