BZOJ 1864 [Zjoi2006]三色二叉树【树形DP】

在这里插入图片描述

#include <bits/stdc++.h>
using namespace std;

const int N=5e5+5;
const int Inf=1e9;

char ch[N];
int n,tot=1,f[N][3],son[N][3];

#define _max(i,j,k) max(max(i,j),k)
#define _min(i,j,k) min(min(i,j),k)

void read(int x) {
	char ch=getchar();
	
	if(ch=='0') return ;
	
	if(ch=='1') {
		tot++;son[x][1]=tot;read(tot);
	}
	
	if(ch=='2') {
		tot++;son[x][1]=tot;read(tot);
		tot++;son[x][2]=tot;read(tot);
	}
}

void dfs1(int x) {
	if(!x) return ;
	
	dfs1(son[x][1]);dfs1(son[x][2]);
	
	f[x][1]=f[son[x][1]][0]+f[son[x][2]][0]+1;f[x][0]=max(f[son[x][1]][0]+f[son[x][2]][1],f[son[x][1]][1]+f[son[x][2]][0]);
}

void dfs2(int x) {
	if(!x) return ;
	
	dfs2(son[x][1]);dfs2(son[x][2]);
	
	f[x][1]=f[son[x][1]][0]+f[son[x][2]][0]+1;f[x][0]=min(f[son[x][1]][0]+f[son[x][2]][1],f[son[x][1]][1]+f[son[x][2]][0]);
}

int main() {
	read(1);
	
	dfs1(1);
	
	printf("%d ",max(f[1][0],f[1][1]));
	
	memset(f,0,sizeof(f));
	
	dfs2(1);
	
	printf("%d ",min(f[1][0],f[1][1]));
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/yanzhenhuai/article/details/83476038