BZOJ 1864: [Zjoi2006]三色二叉树 树形DP_读入

Code:

#include <bits/stdc++.h>
#define setIO(s) freopen(s".in","r",stdin) 
#define maxn 1000000 
#define lson ch[u][0] 
#define rson ch[u][1] 
using namespace std;
int ch[maxn][2], f[maxn], g[maxn]; 
int n = 1; 
void read(int u)
{
    char c = getchar(); 
    if(c == '0') return; 
    ++n, lson = n, read(lson); 
    if(c == '2') ++n, rson = n, read(rson);       
}
void dfs1(int u)
{
    if(!u) return;  
    dfs1(lson), dfs1(rson); 
    f[u] = g[lson] + g[rson] + 1; 
    g[u] = max(f[lson] + g[rson], g[lson] + f[rson]);      
}
void dfs2(int u)
{
    if(!u) return; 
    dfs2(lson), dfs2(rson); 
    f[u] = g[u] = 0; 
    f[u] = g[lson] + g[rson] + 1; 
    g[u] = min(f[lson] + g[rson], g[lson] + f[rson]);    
}
int main()
{
    // setIO("input");
    read(1); 
    dfs1(1); 
    printf("%d ",max(g[1], f[1]));
    dfs2(1); 
    printf("%d\n",min(g[1], f[1]));  
    return 0; 
}

  

猜你喜欢

转载自www.cnblogs.com/guangheli/p/10982705.html