Ilya is working for the company that constructs robots. Ilya writes programs for entertainment robots, and his current project is "Bob", a new-generation game robot. Ilya's boss wants to know his progress so far. Especially he is interested if Bob is better at playing different games than the previous model, "Alice". 

So now Ilya wants to compare his robots' performance in a simple game called "1-2-3". This game is similar to the "Rock-Paper-Scissors" game: both robots secretly choose a number from the set {1, 2, 3} and say it at the same moment. If both robots choose the same number, then it's a draw and noone gets any points. But if chosen numbers are different, then one of the robots gets a point: 3 beats 2, 2 beats 1 and 1 beats 3. 

Both robots' programs make them choose their numbers in such a way that their choice in (i + 1)-th game depends only on the numbers chosen by them in i-th game. 

Ilya knows that the robots will play k games, Alice will choose number a in the first game, and Bob will choose b in the first game. He also knows both robots' programs and can tell what each robot will choose depending on their choices in previous game. Ilya doesn't want to wait until robots play all k games, so he asks you to predict the number of points they will have after the final game. 


-----Input-----

The first line contains three numbers k, a, b (1 ≤ k ≤ 10^18, 1 ≤ a, b ≤ 3). 

Then 3 lines follow, i-th of them containing 3 numbers A_{i}, 1, A_{i}, 2, A_{i}, 3, where A_{i}, j represents Alice's choice in the game if Alice chose i in previous game and Bob chose j (1 ≤ A_{i}, j ≤ 3). 

Then 3 lines follow, i-th of them containing 3 numbers B_{i}, 1, B_{i}, 2, B_{i}, 3, where B_{i}, j represents Bob's choice in the game if Alice chose i in previous game and Bob chose j (1 ≤ B_{i}, j ≤ 3). 


-----Output-----

Print two numbers. First of them has to be equal to the number of points Alice will have, and second of them must be Bob's score after k games.


-----Examples-----
Input
10 2 1
1 1 1
1 1 1
1 1 1
2 2 2
2 2 2
2 2 2

Output
1 9

Input
8 1 1
2 2 1
3 3 1
3 1 3
1 1 1
2 1 1
1 2 3

Output
5 2

Input
5 1 1
1 2 2
2 2 2
2 2 2
1 2 2
2 2 2
2 2 2

Output
0 0



-----Note-----

In the second example game goes like this:

$(1,1) \rightarrow(2,1) \rightarrow(3,2) \rightarrow(1,2) \rightarrow(2,1) \rightarrow(3,2) \rightarrow(1,2) \rightarrow(2,1)$

The fourth and the seventh game are won by Bob, the first game is draw and the rest are won by Alice.

Difficulty: interview

Starter code:

Solutions:

k,a0,b0 = map(int,input().split())
a0,b0 = a0-1,b0-1

A = tuple(tuple(map(lambda c: int(c)-1,input().split())) for _ in range(3))
B = tuple(tuple(map(lambda c: int(c)-1,input().split())) for _ in range(3))

# A chose i and B chose j implies ? will choose ?[i][j]

score = lambda a,b: (int((a-b)%3==1),int((b-a)%3==1))

S = set()

cur = (a0,b0)

while cur not in S:
  S.add(cur)
  a,b = cur
  cur = (A[a][b],B[a][b])

pre = (0,0)
p = (a0,b0)
while k > 0 and p != cur:
  pre = tuple(c+d for c,d in zip(pre,score(*p)))
  a,b = p
  p = (A[a][b],B[a][b])
  k -= 1

if k == 0:
  print(*pre)
  return

# cycle length
L = 1
cnt = score(*cur)
a,b = cur
p = (A[a][b],B[a][b])

while p != cur:
  cnt = tuple(c+d for c,d in zip(cnt,score(*p)))
  L += 1
  a,b = p
  p = (A[a][b],B[a][b])

n = k//L
k -= (k//L)*L
cnt = (cnt[0]*n,cnt[1]*n)

suf = (0,0)
p = cur
while k > 0:
  suf = tuple(c+d for c,d in zip(suf,score(*p)))
  a,b = p
  p = (A[a][b],B[a][b])
  k -= 1

print(*(a+b+c for a,b,c in zip(pre,cnt,suf)))

def readln(): return list(map(int, input().rstrip().split()))


def score_of(x, y):
    if x == y:
        return 0, 0
    elif x == 3 and y == 2:
        return 1, 0
    elif x == 2 and y == 3:
        return 0, 1
    elif x == 2 and y == 1:
        return 1, 0
    elif x == 1 and y == 2:
        return 0, 1
    elif x == 1 and y == 3:
        return 1, 0
    elif x == 3 and y == 1:
        return 0, 1


k, a, b = readln()
A, B = [[0 for i in range(4)] for j in range(4)], [[0 for i in range(4)] for j in range(4)]
for i in range(1, 4):
    a1, a2, a3 = readln()
    A[i][1], A[i][2], A[i][3] = a1, a2, a3
for i in range(1, 4):
    a1, a2, a3 = readln()
    B[i][1], B[i][2], B[i][3] = a1, a2, a3

circle = set()
circle_score = [(0, 0)]
circle_data = []
x, y = a, b
while (x, y) not in circle and k > 0:
    circle.add((x, y))
    circle_data.append((x, y))
    x_, y_ = score_of(x, y)
    circle_score.append((circle_score[-1][0] + x_, circle_score[-1][1] + y_))
    x, y = A[x][y], B[x][y]
    k -= 1

if k == 0:
    print("{} {}".format(circle_score[-1][0], circle_score[-1][1]))
    return

pre_idx = circle_data.index((x, y))
freq = len(circle_data) - pre_idx
fscorea, fscoreb = circle_score[-1][0] - circle_score[pre_idx][0], circle_score[-1][1] - circle_score[pre_idx][1]
p = k // freq
rsa = circle_score[-1][0] + fscorea * p
rsb = circle_score[-1][1] + fscoreb * p
r = k % freq

while r > 0:
    x_, y_ = score_of(x, y)
    rsa += x_
    rsb += y_
    x, y = A[x][y], B[x][y]
    r -= 1
print("{} {}".format(rsa, rsb))


completed={}

alice=[[0,-1,1],[1,0,-1],[-1,1,0]]
bob=[[0,1,-1],[-1,0,1],[1,-1,0]]

def simulate(i):

	nonlocal s,a,b,l,m,completed
	if(str(a)+" "+str(b) in completed):
		return 
	s.append(alice[a-1][b-1])
	temp1 = a
	temp2 = b
	completed[str(a)+" "+str(b)]=i
	a = l[temp1-1][temp2-1]
	b = m[temp1-1][temp2-1]
	simulate(i+1)


k,a,b = list(map(int, input().split()))
l=[]
for i in range(3):
	l.append(list(map(int,input().split())))
m=[]
for i in range(3):
	m.append(list(map(int,input().split())))

s=[]
ali=0
bo=0
simulate(0)
for i in range(completed[str(a)+" "+str(b)]):
	if(k==0):
		break
	k-=1
	if(s[i]==1):
		ali+=1
	elif(s[i] == -1):
		bo+=1
s=s[completed[str(a)+" "+str(b)]:]
awins = s.count(1)
bwins = s.count(-1)
mul = k//len(s)
rem = k%len(s)
ali+=mul*awins
bo+=mul*bwins
for i in range(rem):
	if(s[i]==1):
		ali+=1
	elif(s[i]==-1):
		bo+=1
print(ali,bo)

k, a, b = list(map(int, input().split()))
A = [list(map(int, input().split())) for _ in range(3)]
B = [list(map(int, input().split())) for _ in range(3)]
wina = winb = ca = cb = 0
ls = [(0, 0)]
dic = {}
pre = k
cycle = k
for i in range(k):
    if (a - b + 3) % 3 == 1:
        wina += 1
    elif (a - b + 3) % 3 == 2:
        winb += 1
    ls.append((wina, winb))
    if (a, b) in dic:
        pre = dic[(a, b)]
        cycle = i - pre
        ca = wina - ls[pre + 1][0]
        cb = winb - ls[pre + 1][1]
        break
    dic[(a, b)] = i
    (a, b) = (A[a - 1][b - 1], B[a - 1][b - 1])
wina = ls[(k - pre) % cycle + pre][0] + ca * ((k - pre) // cycle)
winb = ls[(k - pre) % cycle + pre][1] + cb * ((k - pre) // cycle)
print("%d %d" % (wina, winb))


def solve():

    point123 = {(1, 1):None, (1, 2):"Bob", (1, 3):"Alice",
                (2, 1):"Alice", (2, 2):None, (2, 3):"Bob",
                (3, 1):"Bob", (3, 2):"Alice", (3, 3):None}
    map123 = {} # (a, b): (nexta, nextb)
    cycle123 = {} # (a, b): (cyclelen, Alicegain, Bobgain)

    k, a, b = [int(st) for st in input().split(" ")]
    A = [None, None, None, None]
    B = [None, None, None, None]

    for i in range(1, 4):
        A[i] = [None] + [int(st) for st in input().split(" ")]
    for i in range(1, 4):
        B[i] = [None] + [int(st) for st in input().split(" ")]

    for i in range(1, 4):
        for j in range(1, 4):
            map123[(i, j)] = (A[i][j], B[i][j])

    for i in range(1, 4):
        for j in range(1, 4):
            cycle = 1
            again, bgain = int(point123[(i, j)] == "Alice"), int(point123[(i, j)] == "Bob")
            i1, j1 = map123[(i, j)]
            while cycle < 10 and not (i1 == i and j1 == j):
                cycle += 1
                again += int(point123[(i1, j1)] == "Alice")
                bgain += int(point123[(i1, j1)] == "Bob")
                i1, j1 = map123[(i1, j1)]
                
            if cycle < 10:
                cycle123[(i, j)] = (cycle, again, bgain)

    #print("Map", map123, "\nCycle", cycle123)

    ansA, ansB = 0, 0
    while k>0:
        
        if (a, b) in cycle123:
            if k % cycle123[(a, b)][0] == 0:
                ansA += cycle123[(a, b)][1] * k//cycle123[(a, b)][0]
                ansB += cycle123[(a, b)][2] * k//cycle123[(a, b)][0]
                return ansA, ansB
        
        k -= 1
        ansA += int(point123[(a, b)] == "Alice")
        ansB += int(point123[(a, b)] == "Bob")
        a, b = map123[(a, b)]

    return ansA, ansB

ansa, ansb = solve()
print(ansa, ansb)


#!/usr/bin/env python3
# encoding: utf-8



#----------
# Constants
#----------



#----------
# Functions
#----------

# Reads a string from stdin, splits it by space chars, converts each
# substring to int, adds it to a list and returns the list as a result.
def get_ints():
    return [ int(n) for n in input().split() ]


def move(matrix, a, b):
    return matrix[a][b]


def game(a, b):
    res = (a - b) % 3
    if res == 1:
        return (1, 0)
    elif res == 2:
        return (0, 1)
    else:
        return (0, 0)


#----------
# Execution start point
#----------

def __starting_point():
    z = get_ints()
    assert len(z) == 3
    k, a, b = z[0], z[1]-1, z[2]-1

    alice = list()
    for i in range(3):
        z = get_ints()
        assert len(z) == 3
        for j in range(len(z)):
            z[j] -= 1
        alice.append(z.copy())

    bob = list()
    for i in range(3):
        z = get_ints()
        assert len(z) == 3
        for j in range(len(z)):
            z[j] -= 1
        bob.append(z.copy())

    moves = list()
    results = list()
    index = -1
    for m in range(k):
        if (a, b) in moves:
            index = moves.index((a, b))
            break
        moves.append((a, b))
        results.append(game(a, b))
        a, b = move(alice, a, b), move(bob, a, b)

    # periods
    apoint, bpoint = 0, 0
    c = len(moves) - index
    rep = (k - index) // c
    for res in results[index:]:
        da, db = res
        apoint += da
        bpoint += db
    apoint *= rep
    bpoint *= rep

    # after
    rem = (k - index) % c
    for i in range(rem):
        da, db = results[i + index]
        apoint += da
        bpoint += db

    # before
    for res in results[:index]:
        da, db = res
        apoint += da
        bpoint += db

    print(apoint, bpoint)

__starting_point()

k, a, b = [int(i) for i in input().split()]
al = [[int(i) for i in input().split()] for j in range(3)]
bb = [[int(i) for i in input().split()] for j in range(3)]
d, sa, sb, cr = dict(), 0, 0, 0
mat = [[(0, 0), (0, 1), (1, 0)],
       [(1, 0), (0, 0), (0, 1)],
       [(0, 1), (1, 0), (0, 0)]]

while cr < k:
    if (a, b) in list(d.keys()):
        break
    cr += 1
    d[(a, b)] = (sa, sb, cr)
    sc = mat[a - 1][b - 1]
    sa += sc[0]
    sb += sc[1]
    a, b = al[a - 1][b - 1], bb[a - 1][b - 1]

if cr == k:
    print(sa, sb)
    return

ln = cr - d[(a, b)][2] + 1
adda = sa - d[(a, b)][0]
addb = sb - d[(a, b)][1]
left = k - cr
cn = left // ln
sa += cn * adda
sb += cn * addb
cr += ln * cn

while cr < k:
    cr += 1
    sc = mat[a - 1][b - 1]
    sa += sc[0]
    sb += sc[1]
    a, b = al[a - 1][b - 1], bb[a - 1][b - 1]

print(sa, sb)


ka, kb = 0, 0

def g(a, b):
    nonlocal ka, kb
    if a == b:
        return
    if abs(a - b) == 2:
        if a == 1:
            ka += 1
        else:
            kb += 1
    else:
        if a > b:
            ka += 1
        else:
            kb += 1

def main():
    nonlocal ka, kb
    k, a, b = list(map(int, input().split()))
    aa = [[] for i in [1, 1, 1]]
    bb = [[] for i in [1, 1, 1]]
    aa[0] = list(map(int, input().split()))
    aa[1] = list(map(int, input().split()))
    aa[2] = list(map(int, input().split()))
    bb[0] = list(map(int, input().split()))
    bb[1] = list(map(int, input().split()))
    bb[2] = list(map(int, input().split()))
    x = a
    y = b
    o = 1
    c = [[x, y]]
    d = [[0, 0]]
    g(x, y)
    if k == 1:
        return
    x, y = aa[x - 1][y - 1], bb[x - 1][y - 1]
    #print(x, y, ka, kb)
    while [x, y] not in c:
        o += 1
        c += [[x, y]]
        d += [[ka, kb]]
        g(x, y)
        x, y = aa[x - 1][y - 1], bb[x - 1][y - 1]
        #print(x, y, ka, kb)
        if o == k:
            return
    ind = c.index([x, y])
    dka = ka - d[ind][0]
    dkb = kb - d[ind][1]
    delta = o - ind
    kk = (k - ind) // delta - 1
    #print(dka, dkb, delta)
    ka += kk * dka
    kb += kk * dkb
    o += kk * delta
    while o != k:
        o += 1
        g(x, y)
        x, y = aa[x - 1][y - 1], bb[x - 1][y - 1]
        #print(x, y, ka, kb)

main()
print(ka, kb)


from functools import reduce

def get_scores(a, b):
    if a == b:
        return (0, 0)
    elif (a, b) in ((2, 1), (1, 0), (0, 2)):
        return (1, 0)
    else:
        return (0, 1)

def add(t1, t2):
    return tuple(map(sum, list(zip(t1, t2))))

def mul(t, x):
    return t[0] * x, t[1] * x

k, a, b = list(map(int, input().split(' ')))

alice_ts = {}
bob_ts = {}

for ts in (alice_ts, bob_ts):
    for i in range(3):
        xs = list(map(int, input().split(' ')))[::-1]

        for j in range(3):
            ts[(i, j)] = xs.pop() - 1

state = (a - 1, b - 1)

result = (0, 0)

log = {}
step_results = []

start, end = None, None

for i in range(k):
    if state in log:
        start = log[state]
        end = i

        break

    current_res = get_scores(*state)

    result = add(result, current_res)

    log[state] = i
    step_results.append(current_res)

    if end is not None:
        break

    state = alice_ts[state], bob_ts[state]

if end is not None:
    cycle_sum = reduce(add, step_results[start:end])

    total_cycle_sum = mul(cycle_sum, (k - end) // (end - start))

    result = add(result, total_cycle_sum)

    for i in range(0, (k - end) % (end - start)):
        result = add(result, step_results[start + i])

print(result[0], result[1])


R=lambda:list(map(int,input().split()))
k,a,b=R()
a-=1
b-=1
A=[list(R()) for _ in range(3)]
B=[list(R()) for _ in range(3)]
f=[[None]*3 for _ in range(3)]
s=[[0,0]]
i=0
while i<k and f[a][b] is None:
    f[a][b]=i
    s.append(list(s[i]))
    i+=1
    d=a-b
    if d<0:
        d+=3
    if d:
        s[i][d-1]+=1
    a,b=A[a][b]-1,B[a][b]-1
if i==k:
    print(*s[i])
else:
    cb=f[a][b]
    c=i-cb
    m=(k-i)//c
    sa,sb=s[i]
    sa+=m*(sa-s[cb][0])+s[cb+(k-i)%c][0] - s[cb][0]
    sb+=m*(sb-s[cb][1])+s[cb+(k-i)%c][1] - s[cb][1]
    print(sa,sb)


R=lambda:list(map(int,input().split()))
k,a,b=R()
a-=1
b-=1
A=[list(R()) for _ in range(3)]
B=[list(R()) for _ in range(3)]
f=[[None]*3 for _ in range(3)]
s=[[0,0]]
i=0
while i<k and f[a][b] is None:
    f[a][b]=i
    s.append(list(s[i]))
    i+=1
    d=a-b
    if d<0:
        d+=3
    if d:
        s[i][d-1]+=1
    a,b=A[a][b]-1,B[a][b]-1
if i==k:
    print(*s[i])
else:
    cb=f[a][b]
    c=i-cb
    m=(k-i)//c
    sa,sb=s[i]
    sr=s[cb+(k-i)%c]
    sa+=m*(sa-s[cb][0])+sr[0]-s[cb][0]
    sb+=m*(sb-s[cb][1])+sr[1]-s[cb][1]
    print(sa,sb)


R=lambda:list(map(int,input().split()))
k,a,b=R()
a-=1
b-=1
A=[list(R()) for _ in range(3)]
B=[list(R()) for _ in range(3)]
f=[[None]*3 for _ in range(3)]
s=[[0,0]]
i=0
while i<k and f[a][b] is None:
    f[a][b]=i
    s.append(list(s[i]))
    i+=1
    d=a-b
    if d<0:
        d+=3
    if d:
        s[i][d-1]+=1
    a,b=A[a][b]-1,B[a][b]-1
if i==k:
    print(*s[i])
else:
    j=f[a][b]
    z=list(zip(s[i],s[j],s[j+(k-i)%(i-j)]))
    print(*[((k-i)//(i-j)+1)*(x[0]-x[1])+x[2] for x in z])


R=lambda:list(map(int,input().split()))
k,a,b=R()
a-=1
b-=1
A=[list(R()) for _ in range(3)]
B=[list(R()) for _ in range(3)]
f=[[None]*3 for _ in range(3)]
s=[[0,0]]
i=0
while i<k and f[a][b] is None:
    f[a][b]=i
    s.append(list(s[i]))
    i+=1
    d=a-b
    if d<0:
        d+=3
    if d:
        s[i][d-1]+=1
    a,b=A[a][b]-1,B[a][b]-1
if i==k:
    print(*s[i])
else:
    j=f[a][b]
    c,d=divmod(k-i,i-j)
    z=list(zip(s[i],s[j],s[j+d]))
    print(*[(c+1)*(x[0]-x[1])+x[2] for x in z])


class Player:
  __slots__ = ['choices']

  def __init__(self, choices):
    self.choices = choices

  def choose_next(self, row, col):
    return self.choices[row - 1][col - 1]

  def round_score(own, other):
    if own == other + 1 or (own == 1 and other == 3):
      return 1
    return 0

class State:
  __slots__ = ['score_a', 'score_b', 'time']

  def __init__(self, a, b, time):
    self.score_a = a
    self.score_b = b
    self.time = time


def read_player():
  choices = [list(map(int, input().split())) for i in range(3)]
  return Player(choices)

def play(rounds, pa, a, pb, b):
  memo = {}
  score = [0, 0]
  cacat = False

  for i in range(rounds):
    pair = (a, b)
    if pair in memo:
      cycle_len = (i - memo[pair].time)
      cycles = (rounds - i) // cycle_len

      score_a = score[0] - memo[pair].score_a
      score_b = score[1] - memo[pair].score_b

      score[0] += score_a * cycles
      score[1] += score_b * cycles
      rounds -= i + cycles * cycle_len
      cacat = True
      break
    else:
      memo[pair] = State(score[0], score[1], i)

    score[0] += Player.round_score(a, b)
    score[1] += Player.round_score(b, a)
    a, b = pa.choose_next(a, b), pb.choose_next(a, b)

  if cacat:
    for i in range(rounds):
      score[0] += Player.round_score(a, b)
      score[1] += Player.round_score(b, a)
      a, b = pa.choose_next(a, b), pb.choose_next(a, b)

  return score

def main():
  rounds, a, b = list(map(int, input().split()))
  pa = read_player()
  pb = read_player()

  score = play(rounds, pa, a, pb, b)
  print(score[0], score[1])

main()


R=lambda:list(map(int,input().split()))
k,a,b=R()
a-=1
b-=1
A=[list(R()) for _ in range(3)]
B=[list(R()) for _ in range(3)]
f=[[None]*3 for _ in range(3)]
s=[[0,0]]
i=0
while i<k and f[a][b] is None:
    f[a][b]=i
    s.append(list(s[i]))
    i+=1
    d=a-b
    if d<0:
        d+=3
    if d:
        s[i][d-1]+=1
    a,b=A[a][b]-1,B[a][b]-1
if i==k:
    print(*s[i])
else:
    j=f[a][b]
    m,n=divmod(k-i,i-j)
    print(*[(m+1)*(x[0]-x[1])+x[2] for x in zip(s[i],s[j],s[j+n])])


R=lambda:list(map(int,input().split()))
k,a,b=R()
a-=1
b-=1
A=[list(R()) for _ in range(3)]
B=[list(R()) for _ in range(3)]
f=[[None]*3 for _ in range(3)]
s=[[0,0]]
i=0
while i<k and f[a][b] is None:
    f[a][b]=i;s.append(list(s[i]));i+=1;d=a-b
    if d<0:d+=3
    if d:s[i][d-1]+=1
    a,b=A[a][b]-1,B[a][b]-1
if i==k:print(*s[i])
else:
    j=f[a][b];m,n=divmod(k-i,i-j)
    print(*[(m+1)*(x[0]-x[1])+x[2] for x in zip(s[i],s[j],s[j+n])])


def read(): return list(map(int, input().split(' ')))
k, a, b = read()
A = [read() for _ in range(3)]
B = [read() for _ in range(3)]

ra, rb = 0, 0

skipped = False
pos = { (a, b): 0 }
scoreA = { (a, b): 0 }
scoreB = { (a, b): 0 }
if (b - a) % 3 == 1:
    rb = 1
    #scoreB[(a, b)] = rb
elif (b - a) % 3 == 2:
    ra = 1
    #scoreA[(a, b)] = ra

i = 1
while i < k:
    na = A[a-1][b-1]
    nb = B[a-1][b-1]
    #print('game:', na, nb)

    if (na, nb) in pos and not skipped:
        cycleLen = i - pos[(na, nb)]
        cycleScoreA = ra - scoreA[(na, nb)]
        cycleScoreB = rb - scoreB[(na, nb)]

        skipCycles = (k - i) // cycleLen
        #print('Skip:', cycleLen, cycleScoreA, cycleScoreB, skipCycles)
        ra += cycleScoreA * skipCycles
        rb += cycleScoreB * skipCycles
        i += skipCycles * cycleLen

        skipped = True
    else:
        scoreA[(na, nb)] = ra
        scoreB[(na, nb)] = rb
        pos[(na, nb)] = i

        if (nb - na) % 3 == 1:
            rb += 1
            #print(i, '+b', ra, rb)
        elif (nb - na) % 3 == 2:
            ra += 1
            #print(i, '+a', ra, rb)
        
        i += 1
        a, b = na, nb

#print('Answer')
print(ra, rb)
#print('ScoreA')
#print(scoreA)
#print('ScoreB')
#print(scoreB)
#print('pos')
#print(pos)


f = lambda: list(map(int, input().split()))
g = lambda: [[0] * 4] + [[0] + f() for i in range(3)]
h = lambda x, y: x - 1 == y % 3
t = lambda a, b, u, v: (A[a][b], B[a][b], u + h(a, b), v + h(b, a))
k, a, b = f()
p = 2520
s, d = k // p, k % p
if s: s, d = s - 1, d + p
A, B = g(), g()
u = v = x = y = 0
for j in range(d): a, b, u, v = t(a, b, u, v)
for i in range(p): a, b, x, y = t(a, b, x, y)
print(u + x * s, v + y * s)

import sys

def log(s):
#    print(s)
    pass

k, a, b = list(map(int, sys.stdin.readline().strip().split(' ')))
alice = {}
for i in range(3):
    one, two, three = list(map(int, sys.stdin.readline().strip().split(' ')))
    alice[(i + 1, 1)] = one
    alice[(i + 1, 2)] = two
    alice[(i + 1, 3)] = three

bob = {}
for i in range(3):
    one, two, three = list(map(int, sys.stdin.readline().strip().split(' ')))
    bob[(i + 1, 1)] = one
    bob[(i + 1, 2)] = two
    bob[(i + 1, 3)] = three

score = {(1, 1): (0, 0), (2, 2): (0, 0), (3, 3): (0, 0),
        (1, 2): (0, +1), (2, 3): (0, +1), (3, 1): (0, 1),
        (2, 1): (1, 0), (3, 2): (1, 0), (1, 3): (1, 0)}

seen = []
current = (a, b)
while current not in seen:
    seen.append(current)
    current = (alice[current], bob[current])

loop = seen.index(current)
vals = [score[state] for state in seen] 

a_point, b_point = (0, 0)
a_vals, b_vals = list(zip(*vals))
a_point += sum(a_vals[:min(k, loop)])
b_point += sum(b_vals[:min(k, loop)])

k = k - loop
loop_len = len(seen) - loop
a_loop_val = sum(a_vals[loop:])
b_loop_val = sum(b_vals[loop:])
if k >= 0:
    tail = k % loop_len
    num_iters = k // loop_len
    a_point += sum(a_vals[loop:loop+tail])
    b_point += sum(b_vals[loop:loop+tail])
    a_point += num_iters * a_loop_val
    b_point += num_iters * b_loop_val


log(a_point)
log(b_point)
print(round(a_point), round(b_point))



#educational round 29
#two robots play N rounds of game 1 2 3. each choose a number from 1 2 or 3
#game rule 3 win 2, 2 win 1, 1 win against 3
#player choose next number from previous move of both players.
#input format
#line 1:     N a b - N round of games, a b is the number of first round from alice and bob
#line 2 - 4: 3 x 3 grid Aij is next number of Alice if previous A=i, B=j
#line 5 - 7: 3 x 3 grid Bij is next number of Bob if previous A=i, B=j
#output format
#total points of Alice and Bob
class Game123:
    def __init__(self):
        self.alice = [0]*9
        self.bob=[0]*9
        self.moves=[-1]*10
        self.count=0
        self.pointsA=0
        self.pointsB=0

    #convert 3x3 grid into 1D array
    def gameChoice(self, m, r, bBob):
        choice=self.alice
        if bBob:
            choice=self.bob
        for i in range(len(m)):
            choice[3*r+i]=m[i]

    #look if move already exists
    def findMove(self, a, b):
        m=(a-1)*3+b-1
        for i in range(self.count):
            if self.moves[i]==m:
                return i
        #print("a={0} b={1} m={2} count={3}".format(a,b,m, self.count))
        self.moves[self.count]=m
        self.count += 1
        return -1

    def computePoints(self, m):
        #convert m back to a and b, m is  from 0 to 8
        b=m%3+1
        a=m//3+1
        #return positive if alice win
        if a==b:
            return
        if a==3 and b==2 or a==2 and b==1 or a==1 and b==3:
            self.pointsA += 1
        else:
            self.pointsB += 1

    def output(self):
        print("{0} {1}".format(self.pointsA,self.pointsB))    
        
    def startGame(self, a, b, totalmoves):
        #print(self.moves)
        #print(self.alice)
        #print(self.bob)
        found=-1
        while found<0:
            found=self.findMove(a,b)
            m=(a-1)*3+b-1
            a=self.alice[m]  #next move
            b=self.bob[m]
        #print("repeat {0} to {1}".format(found, self.count))
        pointaA=0
        pointsB=0
        # compute moves of no repeats
        if totalmoves <= self.count:
            for i in range(totalmoves):
                self.computePoints(self.moves[i])
        else:
            totalmoves -= found
            repeats = totalmoves//(self.count-found)
            totalmoves %= (self.count-found)
            for i in range(found, self.count): #repeated moves
                self.computePoints(self.moves[i])
            #self.output()
            self.pointsA *= repeats
            self.pointsB *= repeats
            #self.output()
            for i in range(found): #moves before repeat
                self.computePoints(self.moves[i])
            #self.output()
            for i in range(found, totalmoves+found): #odd moves after repeat
                self.computePoints(self.moves[i])
        self.output()

    def test():
        g=Game123()
        g.gameChoice([2,2,1],0,False)
        g.gameChoice([3,3,1],1,False)
        g.gameChoice([3,1,3],2,False)
        g.gameChoice([1,1,1],0,True)
        g.gameChoice([2,1,1],1,True)
        g.gameChoice([1,2,3],2,True)
        g.startGame(1,1,8)

def nia():
    s=input()
    while len(s)==0:
        s=input()
    s=s.split()
    iVal=[];
    for i in range (len(s)):
        iVal.append(int(s[i]))
    return iVal

def solve():
    g=Game123()
    nab=nia()
    for i in range(3):
        g.gameChoice(nia(), i, False)
    for i in range(3):
        g.gameChoice(nia(), i, True)
    g.startGame(nab[1],nab[2],nab[0])
    
solve()  


from decimal import *
#print(getcontext())
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
getcontext().prec = 25

k, a, b = [int(i) for i in input().split(" ")]
A = []
B = []
ap = 0
bp = 0
ac = a
bc = b
ah = []
bh = []
sh = []
alert = 0
for i in range(3):
    A.append(input())
for i in range(3):
    B.append(input())

def Alice_choice(i,j):
    return int((A[i-1])[2*j-2])

def Bob_choice(i,j):
    return int((B[i-1])[2*j-2])

if ac == bc + 1 or ac == bc - 2:
    ap += 1
    ah.append(ac)
    bh.append(bc)
    sh.append(1)
elif bc == ac + 1 or bc == ac - 2:
    bp += 1
    ah.append(ac)
    bh.append(bc)
    sh.append(-1)
else:
    ah.append(ac)
    bh.append(bc)
    sh.append(0)
q = 0
r = 0
for q in range(k-1):
    temp_a = Alice_choice(ac,bc)
    temp_b = Bob_choice(ac,bc)
    ac = temp_a
    bc = temp_b
    if ac == bc + 1 or ac == bc - 2:
        ap += 1
        ah.append(ac)
        bh.append(bc)
        sh.append(1)
    elif bc == ac + 1 or bc == ac - 2:
        bp += 1
        ah.append(ac)
        bh.append(bc)
        sh.append(-1)
    else:
        ah.append(ac)
        bh.append(bc)
        sh.append(0)
    for r in range(q + 1):
        if ac == ah[r] and bc == bh[r]:
            alert = 1
            break
    if alert == 1:
        break
q += 1
period = q - r
score_pp = sh[r+1:q+1]
end = (k - len(sh)) % period
repeat = Decimal(k - len(sh) - end) / period
aadd = 0
badd = 0
for i in score_pp:
    if i == 1:
        aadd += 1
    elif i == -1:
        badd += 1
ap += aadd*repeat
bp += badd*repeat
for i in score_pp[:end]:
    if i == 1:
        ap += 1
    elif i == -1:
        bp += 1

print(ap, end = ' ')
print(bp)

# print(ah)
# print(bh)
# print(sh)
# print(r,q)
# print(score_pp)
# print(period)
# print(end)
# print(repeat)
# print(aadd,badd)

# Time Limit Exceeded #

def readints():
    return [int(item) for item in input().strip().split()]


def cmp(a, b):
    return {
        1: {1: (0, 0), 2: (0, 1), 3: (1, 0)},
        2: {1: (1, 0), 2: (0, 0), 3: (0, 1)},
        3: {1: (0, 1), 2: (1, 0), 3: (0, 0)}
    }[a][b]


class Solver:
    def main(self):
        n, a, b = readints()
        A = [0, [0] + readints(), [0] + readints(), [0] + readints()]
        B = [0, [0] + readints(), [0] + readints(), [0] + readints()]

        current = (a, b)
        results = [current]

        while True:
            current = (A[current[0]][current[1]], B[current[0]][current[1]])
            if current not in results:
                results.append(current)
            else:
                break

        first_cycle = results.index(current)
        totals = 0, 0
        for i in range(first_cycle):
            res = cmp(*results[i])
            totals = totals[0] + res[0], totals[1] + res[1]
            n -= 1
            if n == 0:
                break

        cycled = len(results) - first_cycle
        if n > 0:
            multi = n // cycled
            for i in range(first_cycle, len(results)):
                res = cmp(*results[i])
                totals = totals[0] + multi * res[0], totals[1] + multi * res[1]

            for i in range(n % cycled):
                res = cmp(*results[i + first_cycle])
                totals = totals[0] + res[0], totals[1] + res[1]

        print('{} {}'.format(*totals))


Solver().main()


k,a,b = list(map(int, input().split()))
A = []
B = []
sa , sb = 0,0
r = {
    (1,1):(0,0),
    (1,2):(0,1),
    (1,3):(1,0),
    (2,1):(1,0),
    (2,2):(0,0),
    (2,3):(0,1),
    (3,1):(0,1),
    (3,2):(1,0),
    (3,3):(0,0),
}

p = {}

for _ in range(3):
    A.append(list(map(int, input().split())))
for _ in range(3):
    B.append(list(map(int, input().split())))
i = 0
while (i<k):

    if (a,b) in p:
        j, psa, psb = p[(a,b)]
        l = i-j
        psa = sa-psa
        psb = sb-psb
        rep = (k-i)//l
        sa += psa*rep
        sb += psb*rep
        i+=l*rep
        break;
    else:
        p[(a,b)] = (i,sa,sb)

    t = r[(a,b)]
    sa+=t[0]
    sb+=t[1]
    a,b = A[a-1][b-1], B[a-1][b-1]
    i+=1

while (i<k):

    t = r[(a,b)]
    sa+=t[0]
    sb+=t[1]
    a,b = A[a-1][b-1], B[a-1][b-1]
    i+=1

print(sa,sb)




def winner(q, r):
    if q == r:
        return 'd'
    if q == 0 and r == 2:
        return 'a'
    if r == 0 and q == 2:
        return 'b'
    if q > r:
        return 'a'
    return 'b'


k, a, b = [int(x) - 1 for x in input().split()]
A = [[int(x) - 1 for x in input().split()] for y in range(3)]
B = [[int(x) - 1 for x in input().split()] for z in range(3)]
score = {'a': 0, 'b': 0, 'd': 0}
score[winner(a, b)] += 1
d = {(a, b): 0}
i = 1
j = -1

while k:
    na = A[a][b]
    nb = B[a][b]
    if (na, nb) in list(d.keys()):
        j = d[(na, nb)]
        break
    else:
        d[(na, nb)] = i
        score[winner(na, nb)] += 1
        a = na
        b = nb
    i += 1
    k -= 1

if j == -1:
    print(score['a'], score['b'])
    return

period = {'a': 0, 'b': 0, 'd': 0}
end_score = {'a': 0, 'b': 0, 'd': 0}

rem = k % (i - j)
per = k // (i - j)

for move in d:
    if d[move] < j:
        continue
    if d[move] < j + rem:
        end_score[winner(move[0], move[1])] += 1
    period[winner(move[0], move[1])] += 1

for win in ['a', 'b', 'd']:
    score[win] += end_score[win] + per * period[win]

# print('rem:', rem, 'per:', per, 'period:', period, 'end score:', end_score)

print(score['a'], score['b'])