-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathTHREECOL.cpp
105 lines (93 loc) · 2.28 KB
/
THREECOL.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* THREECOL.cpp
*
* Created on: Apr 6, 2015
* Author: ngoyal
*/
#include<iostream>
#include<cstring>
#define MAX 10005
using namespace std;
int resultMax[MAX][3];
int resultMin[MAX][3];
int pointer;
typedef struct Treenode{
struct Treenode * left;
struct Treenode * right;
int data;
}node;
node * getTree(char *str){
char childCount=str[pointer];
node *root=new node;
root->data=pointer;
pointer++;
if(childCount=='2'){
root->left=getTree(str);
root->right=getTree(str);
}else if(childCount=='1'){
root->left=getTree(str);
root->right=NULL;
}else{
root->left=NULL;
root->right=NULL;
}
return root;
}
int solve(node *root,int color){
if(root==NULL){
return 0;
}
if(resultMax[root->data][color]!=-1){
return resultMax[root->data][color];
}
int score=color==2?1:0;
if(color==2){
score+=max(solve(root->left,1)+solve(root->right,0),solve(root->left,0)+solve(root->right,1));
}else if(color==1){
score+=max(solve(root->left,0)+solve(root->right,2),solve(root->left,2)+solve(root->right,0));
}else{
score+=max(solve(root->left,1)+solve(root->right,2),solve(root->left,2)+solve(root->right,1));
}
resultMax[root->data][color]=score;
return score;
}
int solveMin(node *root,int color){
if(root==NULL){
return 0;
}
if(resultMin[root->data][color]!=-1){
return resultMin[root->data][color];
}
int score=color==2?1:0;
if(color==2){
score+=min(solveMin(root->left,1)+solveMin(root->right,0),solveMin(root->left,0)+solveMin(root->right,1));
}else if(color==1){
score+=min(solveMin(root->left,0)+solveMin(root->right,2),solveMin(root->left,2)+solveMin(root->right,0));
}else{
score+=min(solveMin(root->left,1)+solveMin(root->right,2),solveMin(root->left,2)+solveMin(root->right,1));
}
resultMin[root->data][color]=score;
return score;
}
//0-Red, 1-Blue, 2-Green
int main(){
int T;
cin>>T;
while(T--){
char treeStr[MAX];
cin>>treeStr;
pointer=0;
for(int i=0;i<strlen(treeStr);i++){
resultMax[i][0]=-1;
resultMax[i][1]=-1;
resultMax[i][2]=-1;
resultMin[i][0]=-1;
resultMin[i][1]=-1;
resultMin[i][2]=-1;
}
node * root=getTree(treeStr);
int resultMax=max(solve(root,0),max(solve(root,1),solve(root,2)));
int resultMin=min(solveMin(root,0),min(solveMin(root,1),solveMin(root,2)));
cout<<resultMax<<" "<<resultMin<<"\n";
}
}