import java.util.*;
public class Main {
public static boolean evaluateExpression(String expression, Map<String, String> keyValueMap) {
for (Map.Entry<String, String> entry : keyValueMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
expression = expression.replaceAll(key + " = '" + value + "'", "true");
expression = expression.replaceAll(key + " = '[^']*'", "false");
}
expression = expression.replaceAll("AND", "&&");
expression = expression.replaceAll("OR", "||");
return calculate(expression);
}
public static boolean calculate(String expression) {
Stack<Boolean> stack = new Stack<>();
Stack<String> operators = new Stack<>();
expression = expression.replaceAll("\\s+", "");
int i = 0;
while (i < expression.length()) {
if (expression.charAt(i) == '(') {
operators.push("(");
i++;
} else if (expression.charAt(i) == ')') {
while (!operators.isEmpty() && !"(".equals(operators.peek())) {
boolean b2 = stack.pop();
boolean b1 = stack.pop();
String op = operators.pop();
stack.push(applyOperator(b1, b2, op));
}
operators.pop();
i++;
} else if (expression.startsWith("true", i)) {
stack.push(true);
i += 4;
} else if (expression.startsWith("false", i)) {
stack.push(false);
i += 5;
} else if (expression.startsWith("&&", i)) {
operators.push("&&");
i += 2;
} else if (expression.startsWith("||", i)) {
operators.push("||");
i += 2;
}
}
while (!operators.isEmpty()) {
boolean b2 = stack.pop();
boolean b1 = stack.pop();
String op = operators.pop();
stack.push(applyOperator(b1, b2, op));
}
return stack.pop();
}
public static boolean applyOperator(boolean b1, boolean b2, String op) {
if (op.equals("&&")) {
return b1 && b2;
} else if (op.equals("||")) {
return b1 || b2;
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
sc.nextLine();
String[] expressions = new String[n];
for (int i = 0; i < n; i++) {
expressions[i] = sc.nextLine();
}
Map<String, String> keyValueMap = new HashMap<>();
for (int i = 0; i < m; i++) {
String key = sc.next();
String value = sc.next();
keyValueMap.put(key, value);
}
for (String expr : expressions) {
boolean result = evaluateExpression(expr, keyValueMap);
if (result) {
System.out.println(0);
} else {
System.out.println(1);
}
}
sc.close();
}
}