#include<stdio.h>
#include<string.h>
#include<math.h>
#include<ctype.h>
replace(char firstString[], char secondString[], char thirdString[], int which);
char expression[1001], copyExp[1001];
int boolVar[27];
int main(){
FILE *file1, *file2;
int i=-1, j=0, nChanges;
char ch[2], val[2], letters[1001];
file1 = fopen("bool.in", "r");
file2 = fopen("bool.out", "w");
while(1){
expression[++i] = fgetc(file1);
if(expression[i]=='\n'){
expression[i] = '\0';
break;
}
}
replace("TRUE", "1", expression, 1);
replace("FALSE", "0", expression, 1);
replace("AND", "&", expression, 1);
replace("OR", "|", expression, 1);
replace("NOT", "-", expression, 1);
replace(" ", "", expression, 1);
fscanf(file1, "%d", &nChanges);
fscanf(file1, "%s", letters);
while(nChanges){
strcpy(copyExp, expression);
boolVar[letters[j++] - 65] = 1 - boolVar[letters[j] - 65];
for(i=0; i<strlen(copyExp); i++){
if(isalpha(copyExp[i])){
ch[0] = copyExp[i]; ch[1] = '\0';
val[0] = (boolVar[copyExp[i]-65] + '0'); val[1] = '\0';
replace(ch, val, copyExp, 0);
}
}
while(1){
replace("-0", "1", copyExp, 0); // NOT
replace("-1", "0", copyExp, 0);
replace("0&0", "0", copyExp, 0); // AND
replace("1&0", "0", copyExp, 0);
replace("0&1", "0", copyExp, 0);
replace("1&1", "1", copyExp, 0);
replace("0|0", "0", copyExp, 0); // OR
replace("1|0", "1", copyExp, 0);
replace("0|1", "1", copyExp, 0);
replace("1|1", "1", copyExp, 0);
replace("(1)", "1", copyExp, 0); // ()
replace("(0)", "0", copyExp, 0);
if(strlen(copyExp)==1)
break;
}
fprintf(file2, "%c", copyExp[0]);//-------------
nChanges--;
}
return 0;
}
replace(char firstString[], char secondString[], char thirdString[], int which){
char newString[1000];
int i, j, k, len1, len2, len3, result=-1;
len1 = strlen(firstString);
len2 = strlen(secondString);
len3 = strlen(thirdString);
for(i=0; i<=len3-len1; i++){
if(thirdString[i]==firstString[0]){
for(j=0; j<len1; j++){
if(firstString[j]!=thirdString[i+j])
break;
}
if(j==len1){
result = i;
}
}
}
if(result!=-1){
while(result!=-1){
for(i=0; i<result; i++){
newString[i] = thirdString[i];
}
for(j=0; j<len2; j++){
newString[i++] = secondString[j];
}
for(k=result+len1; k<len3+abs(len2-len1); k++){
newString[i++] = thirdString[k];
}
newString[i] = '\0';
strcpy(thirdString, newString);
result = -1;
for(i=0; i<=len3-len1; i++){
if(thirdString[i]==firstString[0]){
for(j=0; j<len1; j++){
if(firstString[j]!=thirdString[i+j])
break;
}
if(j==len1){
result = i;
}
}
}
}
if(which)
strcpy(expression, thirdString);
else
strcpy(copyExp, thirdString);
}
}