https://www.acmicpc.net/problem/14891
def turn(turned, i, d):
turned[i] = True
# 왼쪽 맞으면
if i-1 >= 0 and not turned[i-1] and wheels[i-1][2] != wheels[i][6]:
turn(turned, i-1, -d)
# 오른쪽 맞으면
if i+1 <= 3 and not turned[i+1] and wheels[i][2] != wheels[i+1][6]:
turn(turned, i+1, -d)
wheels[i].rotate(d)
# init
from collections import deque
import sys
read = sys.stdin.readline
wheels = [deque(map(int, read().rstrip())) for _ in range(4)]
k = int(read())
orders = [list(map(int, read().split())) for _ in range(k)]
# start
for num, d in orders:
turned = [False] * 4
turn(turned, num - 1, d)
print(sum([wheels[i][0] * (2 ** i) for i in range(4)]))