三色二叉树

 

 1 #define MAXN 10150UL
 2 
 3 #include<cstdio>
 4 #include<cstring>
 5 #include<iostream>
 6 
 7 using namespace std;
 8 struct Node{
 9     int fa,sd,id,son[3];
10 }op[MAXN];
11 int cnt,p,maxn[MAXN][3],minn[MAXN][3];
12 int maxans=0,minans=505290270;
13 string s;
14 int MIN(int a,int b){
15     if(a<b) return a;
16     else return b;
17 }
18 int MAX(int a,int b){
19     if(a<b) return b;
20     else return a;
21 }
22 void dfs(int x){
23 //    printf("%d\n",p);
24     op[++cnt].fa=x;
25     if(op[x].son[1]) op[x].son[2]=cnt;
26     else op[x].son[1]=cnt;
27     op[cnt].id=cnt;
28     op[cnt].sd=s[p]-'0';
29     int os=cnt;
30     for(int i=1;i<=op[os].sd;i++){
31         p++;
32         dfs(os);
33     }
34 }
35 //green 0   red 1   blue 2 
36 void dp(int x){
37     if(op[x].sd==0){
38         maxn[x][0]=1;
39         minn[x][0]=1;
40         minn[x][1]=0;
41         minn[x][2]=0;
42         return ;
43     }
44     for(int i=1;i<=op[x].sd;i++){
45         dp(op[x].son[i]);
46     }
47     if(op[x].sd==1){
48         int t=op[x].son[1];
49         maxn[x][0]=MAX(maxn[t][1],maxn[t][2])+1;
50         maxn[x][1]=MAX(maxn[t][0],maxn[t][2]);
51         maxn[x][2]=MAX(maxn[t][0],maxn[t][1]);
52         minn[x][0]=MIN(minn[t][1],minn[t][2])+1;
53         minn[x][1]=MIN(minn[t][0],minn[t][2]);
54         minn[x][2]=MIN(minn[t][0],minn[t][1]);
55     }
56     else{
57         int t=op[x].son[1]; int k=op[x].son[2];
58         maxn[x][0]=MAX(maxn[t][1]+maxn[k][2],maxn[t][2]+maxn[k][1])+1;
59         maxn[x][1]=MAX(maxn[t][0]+maxn[k][2],maxn[t][2]+maxn[k][0]);
60         maxn[x][2]=MAX(maxn[t][0]+maxn[k][1],maxn[t][1]+maxn[k][0]);
61         minn[x][0]=MIN(minn[t][1]+minn[k][2],minn[t][2]+minn[k][1])+1;
62         minn[x][1]=MIN(minn[t][0]+minn[k][2],minn[t][2]+minn[k][0]);
63         minn[x][2]=MIN(minn[t][0]+minn[k][1],minn[t][1]+minn[k][0]);
64     }
65     
66 }
67 int main(){
68 /*    freopen("trot.in","r",stdin);
69     freopen("trot.ans","w",stdout);*/
70     cin>>s;
71     dfs(0);
72 /*    for(int i=1;i<=cnt;i++){
73         printf("%d\n",op[i].sd);
74     }*/
75     memset(minn,30,sizeof(minn));
76     dp(1);    
77 /*    for(int i=1;i<=cnt;i++)
78     printf("%d %d %d\n",minn[i][0],minn[i][1],minn[i][2]);*/
79     printf("%d %d",MAX(MAX(maxn[1][0],maxn[1][1]),maxn[1][2]),MIN(MIN(minn[1][0],minn[1][1]),minn[1][2]));
80 }
View Code

 

posted @ 2015-10-11 18:31  Lenicodes  阅读(515)  评论(0编辑  收藏  举报