bzoj1864 [Zjoi2006]三色二叉树(树形dp)

dp[x][0/1]表示x绿/不绿 子树内的绿点个数最多/少。
分别转移一下即可。

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 500010
int n,c[N][2],dp[N][2],owo=0,rt;
char s[N];
inline void dfs1(int &x){
    x=++owo;if(s[x]=='0') return;
    if(s[x]>='1') dfs1(c[x][0]);
    if(s[x]=='2') dfs1(c[x][1]);
}
inline void dfs2(int x){
    dp[x][1]=1;dp[x][0]=0;
    if(c[x][0]) dfs2(c[x][0]);
    if(c[x][1]) dfs2(c[x][1]);
    dp[x][1]+=dp[c[x][0]][0]+dp[c[x][1]][0];
    dp[x][0]=max(dp[c[x][0]][1]+dp[c[x][1]][0],dp[c[x][0]][0]+dp[c[x][1]][1]);
}
inline void dfs3(int x){
    dp[x][1]=1;dp[x][0]=0;
    if(c[x][0]) dfs3(c[x][0]);
    if(c[x][1]) dfs3(c[x][1]);
    dp[x][1]+=dp[c[x][0]][0]+dp[c[x][1]][0];
    dp[x][0]=min(dp[c[x][0]][1]+dp[c[x][1]][0],dp[c[x][0]][0]+dp[c[x][1]][1]);
}
int main(){
//  freopen("a.in","r",stdin);
    scanf("%s",s+1);n=strlen(s+1);
    dfs1(rt);dfs2(rt);
    printf("%d ",max(dp[rt][0],dp[rt][1]));
    memset(dp,0,sizeof(dp));dfs3(rt);
    printf("%d\n",min(dp[rt][0],dp[rt][1]));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/icefox_zhx/article/details/80717449