题目链接
题意:
给出一棵树(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;
}