#include using namespace std; int l[26] = {0}; stack st; vector q; int main() { freopen ("calculate.in", "r", stdin); freopen ("calculate.out", "w", stdout); string s; int n, a; char c; cin >> s; cin >> n; for (int i = 0; i < n; i ++) { cin >> c >> a; l[c - 'a'] = a; } for (int i = 0; i < s.size(); i ++) { if (isalpha(s[i])) { s[i] = l[s[i] - 'a'] + '0'; } } for (int i = 0; i < s.size(); i ++) { if (isdigit(s[i])) q.push_back(s[i]); if (s[i] == '(') { st.push(s[i]); } else if (s[i] == ')') { while (st.top() != '(') { q.push_back(st.top()); st.pop(); } st.pop(); } else { if (s[i] == '~') { st.push(s[i]); } else if (s[i] == '&') { stack tmp; while (st.size()) { if (st.top() != '~') break; tmp.push(st.top()); st.pop(); } st.push(s[i]); while(tmp.size()) { st.push(tmp.top()); tmp.pop(); } } else if (s[i] == '|') { while (st.size()) { if (st.top() == '(') break; q.push_back(st.top()); st.pop(); } st.push(s[i]); } } } while(st.size()) { q.push_back(st.top()); st.pop(); } for (int i = 0; i < q.size(); i ++) { if (q[i] != '1' && q[i] != '0') { if (q[i] == '~') { q.erase(q.begin() + i, q.begin() + i + 1); i --; if (q[i] == '1') q[i] = '0'; else q[i] = '1'; } else if (q[i] == '&') { char c; if (q[i-1] == q[i-2] && q[i-1] == '1') c = '1'; else c = '0'; q.erase(q.begin() + i - 1, q.begin() + i + 1); i -= 2; q[i] = c; } else { char c; if (q[i-1] == q[i-2] && q[i-1] == '0') c = '0'; else c = '1'; q.erase(q.begin() + i - 1, q.begin() + i + 1); i -= 2; q[i] = c; } } } cout << q[0] << endl; fclose(stdout); return 0; }