#include
#include
using namespace std;
int circle[5][8];
int k;
int pow(int a, int n) {
int ret = 1;
for (int i = 0; i < n; i++) {
ret *= a;
}
return ret;
}
void rotate(int type, int d) {
if (d == 1) { // 시계
int tmp = circle[type][7];
for (int i = 6; 0 <= i; i--) {
circle[type][i + 1] = circle[type][i];
}
circle[type][0] = tmp;
}
else { //반 시계
int tmp = circle[type][0];
for (int i = 0; i <= 6; i++) {
circle[type][i] = circle[type][i + 1];
}
circle[type][7] = tmp;
}
}
void func(int n, int d) {
if (n == 1) {
if (circle[n][2] != circle[2][6]) {
if (circle[2][2] != circle[3][6]) {
if (circle[3][2] != circle[4][6]) {
rotate(2, (-1)*d);
rotate(3, d);
rotate(4, (-1)*d);
}
else {
rotate(2, (-1)*d);
rotate(3, d);
}
}
else {
rotate(2, (-1)*d);
}
}
}
else if (n == 2) {
if (circle[n][6] != circle[1][2]) {
rotate(1, (-1)*d);
}
if (circle[n][2] != circle[3][6]) {
if (circle[3][2] != circle[4][6]) {
rotate(3, (-1)*d);
rotate(4, d);
}
else {
rotate(3, (-1)*d);
}
}
}
else if (n == 3) {
if (circle[n][2] != circle[4][6]) {
rotate(4, (-1)*d);
}
if (circle[n][6] != circle[2][2]) {
if (circle[2][6] != circle[1][2]) {
rotate(2, (-1)*d);
rotate(1, d);
}
else {
rotate(2, (-1)*d);
}
}
}
else { // n == 4
if (circle[n][6] != circle[3][2]) {
if (circle[3][6] != circle[2][2]) {
if (circle[2][6] != circle[1][2]) {
rotate(3, (-1)*d);
rotate(2, d);
rotate(1, (-1)*d);
}
else {
rotate(3, (-1)*d);
rotate(2, d);
}
}
else {
rotate(3, (-1)*d);
}
}
}
rotate(n, d);
}
int main(void) {
for (int i = 1; i <= 4; i++) {
for (int j = 0; j < 8; j++) {
scanf("%1d", &circle[i][j]);
}
}
int num, direct;
cin >> k;
for (int i = 0; i < k; i++) {
cin >> num >> direct;
func(num, direct);
}
int ret = 0;
for (int i = 1; i <= 4; i++) {
if (circle[i][0] == 1) ret += pow(2, i - 1);
}
cout << ret << endl;
return 0;
}