#include <stdio.h>
#include <iostream>
#include <string.h>
#include <fstream>
#define MAX_S 100000
char s[MAX_S];
int n;
int sIndex;
char operators[MAX_S];
int operatorsSize;
int factors[MAX_S];
int factorsSize;
int priority(char op) {
if(op=='N'){
return 3;
}else if(op=='A'){
return 2;
}else if(op=='O'){
return 1;
}
return 0;
}
void pushOperator(char op) {
if (op=='N'||op=='O'||op=='A'||op=='('||op==')')
operators[operatorsSize++] = op;
}
char popOperator() {
return operatorsSize ? operators[--operatorsSize] : '\0';
}
char topOperator() {
return operatorsSize ? operators[operatorsSize - 1] : '\0';
}
bool hasOperators() {
return operatorsSize>0;
}
void pushFactor(int factor) {
factors[factorsSize++]=factor;
}
int popFactor() {
return factorsSize ? factors[--factorsSize] : 0;
}
int compute(char op) {
int result,a,b;
result = 0;
if(op=='N'){
a=popFactor();
result=a*-1;
}else if(op=='O'){
a=popFactor();
b=popFactor();
if(a==1||b==1){
result=1;
}else{
result=-1;
}
}else if(op=='A'){
a=popFactor();
b=popFactor();
if(a==1&&b==1){
result=1;
}else{
result=-1;
}
}
return result;
}
void computeTop() {
int a,b;
pushFactor(compute(popOperator()));
}
int factor() {
int number;
number=0;
while(s[sIndex]>='0' && s[sIndex]<='9') {
number=number*10+s[sIndex]-'0';
sIndex++;
}
return number;
}
int main() {
std::ifstream ffin("bool.in");
int k;
std::string modificari;
FILE *fin, *fout;
fin=fopen("bool.in","r");
fout=fopen("bool.out","w");
fgets(s,MAX_S,fin);
n=strlen(s);
sIndex=0;
getline(ffin,modificari);
getline(ffin,modificari);
k=stoi(modificari);
getline(ffin,modificari);
for(int i=1;i<=k;i++){
sIndex=0;
factorsSize=0;
operatorsSize=0;
memset(factors,0,MAX_S);
memset(operators,0,MAX_S);
while(sIndex<n){
if(s[sIndex]>='A'&&s[sIndex]<='Z'&¬((s[sIndex]=='A'&&s[sIndex+1]=='N')||(s[sIndex]=='N'&&s[sIndex+1]=='O')||(s[sIndex]=='O'&&s[sIndex+1]=='R'))){
factors[factorsSize]=-1;
if((s[sIndex]=='T' && s[sIndex+1]=='R')){
factors[factorsSize]=1;
sIndex+=3;
}else if(s[sIndex]=='F'&&s[sIndex+1]=='A'){
sIndex+=4;
}else{
int j=1;
for(char ch:modificari){
if(j>i){
break;
}
if(s[sIndex]==ch){
factors[factorsSize]*=-1;
}
j++;
}
}
factorsSize++;
sIndex++;
}else if(s[sIndex]=='(')
pushOperator(s[sIndex++]);
else if(s[sIndex] ==')') {
while(topOperator()!='('){
computeTop();
}
popOperator();
sIndex++;
}else if(priority(s[sIndex])) {
while(priority(topOperator()) && priority(topOperator())>=priority(s[sIndex]))
computeTop();
pushOperator(s[sIndex]);
if(s[sIndex]=='O'){
sIndex+=2;
}else{
sIndex+=3;
}
}else
sIndex++;
}
while(hasOperators())
computeTop();
int result=popFactor();
if(result==-1){
result=0;
}
fprintf(fout,"%d",result);
}
fclose(fin);
fclose(fout);
return 0;
}