https://www.acmicpc.net/problem/17140
from collections import Counter
from functools import cmp_to_key
def mycmp(x, y):
if x[1] != y[1]:
return x[1] - y[1]
return x[0] - y[0]
def sort():
for i in range(len(a)):
counter = Counter(a[i])
line = sorted([[x, y] for x,y in counter.items() if x != 0], key=cmp_to_key(mycmp))
a[i] = sum(line, [])
max_len = max([len(line) for line in a])
for i in range(len(a)):
a[i] += [0] * (max_len-len(a[i]))
if len(a[i]) > 100:
a[i] = a[i][:100]
# init
import sys
read = sys.stdin.readline
r,c,k=map(int,read().split())
a = [list(map(int, read().split())) for _ in range(3)]
# start
answer = -1
for t in range(101):
if 0 <= r-1 < len(a) and 0 <= c-1 < len(a[0]) and a[r-1][c-1] == k:
answer = t
break
if len(a) >= len(a[0]):
sort()
else:
a = [list(line) for line in zip(*a)]
sort()
a = [list(line) for line in zip(*a)]
print(answer)