Harryxun/testdata huggingface dataset:
Buggy python submission (verdict: Runtime Error):
from math import gcd


H, W, A, B = map(int, input().split())
gcd_hw = gcd(H, W)
gcd_ab = gcd(A, B)
if H == 1:
    print("1" * A + "0" * (W - A))
    exit()
if W == 1:
    print(*("1" * B + "0" * (H - B)), sep="\n")
    exit()

if H // gcd_hw == B // gcd_ab and W // gcd_hw == A // gcd_ab:
    ans = [[0] * W for _ in range(H)]
    for i in range(H):
        for j in range(A):
            ans[i][(j + B * i) % W] = 1
    [print("".join(map(str, row))) for row in ans]
else:
    print("No")


Fixed submission:
H, W, A, B = map(int, input().split())
for _ in range(B):
    print("0" * A + "1" * (W - A))
for _ in range(H - B):
    print("1" * A + "0" * (W - A))
Buggy python submission (verdict: Runtime Error):
from heapq import heapify, heappop, heappush


N, M = map(int, input().split())
A = list(map(lambda x: -int(x), input().split()))
if N == 1:
    print(N >> M)
    exit()
heapify(A)
for i in range(M):
    a = -heappop(A)
    while a >= -A[0]:
        a >>= 1
    heappush(A, -a)
    print(A)
print(-sum(A))

Fixed submission:
from heapq import heapify, heappop, heappush


N, M = map(int, input().split())
A = list(map(lambda x: -int(x), input().split()))
if N == 1:
    print(N >> M)
    exit()
heapify(A)
while M > 0:
    a = -heappop(A)
    while M > 0 and a >= -A[0]:
        a >>= 1
        M -= 1
    heappush(A, -a)
print(-sum(A))
Buggy python submission (verdict: Runtime Error):
N, *A = map(int, open(0).read().split())

A = [0] + A
B = [0] * (N + 1)
sum_B = 0
for i in range(N, 0, -1):
    if sum(B[j] for j in range(i, N + 1, i)) % 2 != A[i]:
        B[i] = 1
        sum_B += 1
print(sum_B)
print(*[i for i, b in enumerate(B) if b])


Fixed submission:
from bisect import bisect_left


def solve():
    S = input()
    T = input()
    if not set(T) <= set(S):
        return -1

    pos = {c: [] for c in "abcdefghijklmnopqrstuvwxyz"}
    for i, c in enumerate(S):
        pos[c].append(i)
    ans = 0
    cur_pos = 0
    for t in T:
        nxt_idx = bisect_left(pos[t], cur_pos)
        if nxt_idx == len(pos[t]):
            ans += len(S)
            cur_pos = 0
            nxt_idx = bisect_left(pos[t], cur_pos)
            cur_pos = pos[t][nxt_idx] + 1
        else:
            cur_pos = pos[t][nxt_idx] + 1

    return ans + cur_pos


print(solve())
Buggy python submission (verdict: Runtime Error):
L, R = map(int, input().split())
MOD = 2019
L %= MOD
R %= MOD
print(min(i * j % 2019 for i in range(L, R) for j in range(i + 1, R + 1)))


Fixed submission:
L, R = map(int, input().split())
MOD = 2019
ans = float("inf")
for i in range(L, R):
    for j in range(i + 1, R + 1):
        ans = min(ans, i * j % MOD)
        if ans == 0:
            print(0)
            exit()
print(ans)
Buggy python submission (verdict: Runtime Error):
def f(n):
    if memo[n] > 0:
        return memo[n]
    memo[n] = f(n - 1) + f(n - 2)
    return memo[n]


N, M, *A = map(int, open(0).read().split())
memo = [1, 1] + [-1] * (N + 10)
A = list(A) + [N + 1]
MOD = 10 ** 9 + 7
ans = 1
prev = 0
for a in A:
    if a == prev:
        ans = 0
        break
    ans *= f(a - 1 - prev)
    ans %= MOD
    prev = a + 1
print(ans)


Fixed submission:
import sys


sys.setrecursionlimit(10 ** 6)


def f(n):
    if memo[n] > 0:
        return memo[n]
    memo[n] = f(n - 1) + f(n - 2)
    return memo[n]


N, M, *A = map(int, open(0).read().split())
memo = [1, 1] + [-1] * N
A = list(A) + [N + 1]
MOD = 10 ** 9 + 7
ans = 1
prev = 0
for a in A:
    if a == prev:
        ans = 0
        break
    ans *= f(a - 1 - prev)
    ans %= MOD
    prev = a + 1
print(ans)

Buggy python submission (verdict: Runtime Error):
def f(n):
    if memo[n] > 0:
        return memo[n]
    else:
        memo[n] = f(n - 1) + f(n - 2)
        return memo[n]


N, M, *A = map(int, open(0).read().split())
memo = [-1] * (N + 2)
memo[0] = 1
memo[1] = 1
A = list(A) + [N + 1]
MOD = 10 ** 9 + 7
ans = 1
prev = 0
for a in A:
    if a == prev:
        ans = 0
        break
    ans *= f(a - 1 - prev)
    ans %= MOD
    prev = a + 1
print(ans)


Fixed submission:
import sys


sys.setrecursionlimit(10 ** 6)


def f(n):
    if memo[n] > 0:
        return memo[n]
    memo[n] = f(n - 1) + f(n - 2)
    return memo[n]


N, M, *A = map(int, open(0).read().split())
memo = [1, 1] + [-1] * N
A = list(A) + [N + 1]
MOD = 10 ** 9 + 7
ans = 1
prev = 0
for a in A:
    if a == prev:
        ans = 0
        break
    ans *= f(a - 1 - prev)
    ans %= MOD
    prev = a + 1
print(ans)

Buggy python submission (verdict: Runtime Error):
def f(n):
    if memo[n] > 0:
        return memo[n]
    else:
        return f(n - 1) + f(n - 2)


N, M, *A = map(int, open(0).read().split())
memo = [-1] * (N + 2)
memo[0] = 1
memo[1] = 1
A = list(A) + [N + 1]
MOD = 10 ** 9 + 7
ans = 1
prev = 0
for a in A:
    if a == prev:
        ans = 0
        break
    ans *= f(a - 1 - prev)
    ans %= MOD
    prev = a + 1
print(ans)


Fixed submission:
import sys


sys.setrecursionlimit(10 ** 6)


def f(n):
    if memo[n] > 0:
        return memo[n]
    memo[n] = f(n - 1) + f(n - 2)
    return memo[n]


N, M, *A = map(int, open(0).read().split())
memo = [1, 1] + [-1] * N
A = list(A) + [N + 1]
MOD = 10 ** 9 + 7
ans = 1
prev = 0
for a in A:
    if a == prev:
        ans = 0
        break
    ans *= f(a - 1 - prev)
    ans %= MOD
    prev = a + 1
print(ans)
Buggy python submission (verdict: Runtime Error):
from heapq import heappop, heapify


N, K, *V = map(int, open(0).read().split())

# i: 操作回数
# j: iのうち戻す回数
# k: i - j のうち左から取り出す範囲 [0, k)
ans = 0
for i in range(K + 1):
    res = 0
    pq = []
    for j in range(i // 2 + 1):
        for k in range(i - j + 1):
            put_out_cnt = j
            tmp = V[:k]
            l = i - j - k
            if l > 0:
                tmp += V[-l:]
            heapify(tmp)
            while put_out_cnt > 0:
                heappop(tmp)
                put_out_cnt -= 1
            ans = max(ans, sum(tmp))
print(ans)



Fixed submission:
N, K = map(int, input().split())
V = list(map(int, input().split()))

ans = 0
for a_plus_b in range(min(N, K) + 1):
    for a in range(a_plus_b + 1):
        b = a_plus_b - a
        gems = V[:a]
        if b > 0:
            gems += V[-b:]
        gems.sort()
        negative_gems = [g for g in gems if g < 0]
        ans = max(ans, sum(gems) - sum(negative_gems[:K - a_plus_b]))
print(ans)
Buggy python submission (verdict: Time Limit Exceeded):
from heapq import heapify, heappush, heappop


(N, M), *AB = [list(map(int, s.split())) for s in open(0)]
A = AB[0]
heapify(A)
for b, c in AB[1:]:
    while b > 0 and c > A[0]:
        a = heappop(A)
        heappush(A, c)
        b -= 1
print(sum(A))

Fixed submission:
(N, M), *AB = [list(map(int, s.split())) for s in open(0)]
A = sorted(AB[0])
D = []
for b, c in sorted(AB[1:], key=lambda x: (-x[1], x[0])):
    D.extend([c] * b)
    if len(D) >= N:
        D = D[:N]
        break
D = D[::-1]
for i in range(N):
    if not D or D[-1] <= A[i]:
        break
    A[i] = D.pop()

print(sum(A))

Buggy python submission (verdict: Time Limit Exceeded):
from heapq import heapify, heappush, heappop


(N, M), *AB = [list(map(int, s.split())) for s in open(0)]
A = AB[0]
heapify(A)
for b, c in AB[1:]:
    while b > 0 and c > A[0]:
        a = heappop(A)
        heappush(A, c)
        b -= 1
print(sum(A))

Fixed submission:
(N, M), *AB = [list(map(int, s.split())) for s in open(0)]
A = sorted(AB[0])
D = []
for b, c in sorted(AB[1:], key=lambda x: (-x[1], x[0])):
    D.extend([c] * b)
    if len(D) >= N:
        D = D[:N]
        break
D = D[::-1]
for i in range(N):
    if not D or D[-1] <= A[i]:
        break
    A[i] = D.pop()

print(sum(A))
Buggy python submission (verdict: Time Limit Exceeded):
R, G, B, N = map(int, input().split())
LIM = 3003
ans = 0
for r in range(LIM):
    for g in range(LIM):
        if R * r + G * g > N:
            break
        Bb = N - R * r - G * g
        if Bb % B == 0:
            ans += 1
print(ans)


Fixed submission:
def solve():
    R, G, B, N = map(int, input().split())
    LIM = 3001
    ans = 0
    for r in range(LIM):
        for g in range(LIM):
            if R * r + G * g > N:
                break
            Bb = N - R * r - G * g
            if Bb % B == 0:
                ans += 1
    return ans


print(solve())
Buggy python submission (verdict: Time Limit Exceeded):
from itertools import combinations
from functools import reduce
from collections import Counter


MOD = 10 ** 9 + 7
N = int(input())
S = input()
cnt = Counter(S)
ans = 0
for i in range(1, N + 1):
    for cs in combinations("abcdefghijklmnopqrstuvwxyz", i):
        ans += reduce(lambda x, y: x * y, [cnt[c] for c in cs])
        ans %= MOD
print(ans)


Fixed submission:
from collections import Counter


MOD = 10 ** 9 + 7
input()
S = input()
ans = 1
for v in Counter(S).values():
    ans *= v + 1
    ans %= MOD
print(ans - 1)

Buggy python submission (verdict: Time Limit Exceeded):
from itertools import combinations
from functools import reduce
from collections import Counter


N = int(input())
S = input()
cnt = Counter(S)
ans = 0
for i in range(1, N + 1):
    for cs in combinations("abcdefghijklmnopqrstuvwxyz", i):
        ans += reduce(lambda x, y: x * y, [cnt[c] for c in cs])
print(ans)



Fixed submission:
from collections import Counter


MOD = 10 ** 9 + 7
input()
S = input()
ans = 1
for v in Counter(S).values():
    ans *= v + 1
    ans %= MOD
print(ans - 1)
Buggy python submission (verdict: Runtime Error):
def dfs(i, j, c):
    visited[i][j] = 1
    current.append((i, j))
    for di, dj in (1, 0), (-1, 0), (0, 1), (0, -1):
        ni, nj = i + di, j + dj
        if not (0 <= ni < H and 0 <= nj < W and not visited[ni][nj]):
            continue
        if S[ni][nj] == c:
            continue
        dfs(ni, nj, not c)


H, W = map(int, input().split())
S = [[c == "#" for c in input()] for _ in range(H)]

ans = 0
visited = [[0] * W for _ in range(H)]
for i in range(H):
    for j in range(W):
        if S[i][j] and not visited[i][j]:
            current = []
            dfs(i, j, True)
            b, w = 0, 0
            for k, l in current:
                if S[k][l]:
                    b += 1
                else:
                    w += 1
            ans += b * w
print(ans)


Fixed submission:
from sys import setrecursionlimit


def dfs(i, j, c):
    visited[i][j] = 1
    current.append((i, j))
    for di, dj in (1, 0), (-1, 0), (0, 1), (0, -1):
        ni, nj = i + di, j + dj
        if not (0 <= ni < H and 0 <= nj < W and not visited[ni][nj]):
            continue
        if S[ni][nj] == c:
            continue
        dfs(ni, nj, not c)


setrecursionlimit(2 * 10 ** 5)
H, W = map(int, input().split())
S = [[c == "#" for c in input()] for _ in range(H)]

ans = 0
visited = [[0] * W for _ in range(H)]
for i in range(H):
    for j in range(W):
        if S[i][j] and not visited[i][j]:
            current = []
            dfs(i, j, True)
            b, w = 0, 0
            for k, l in current:
                if S[k][l]:
                    b += 1
                else:
                    w += 1
            ans += b * w
print(ans)
Buggy python submission (verdict: Time Limit Exceeded):
import numpy as np

n = int(input())
dp = np.zeros((n + 1, 3), dtype=int)
for i in range(n):
    abc = list(map(int, input().split()))
    for j in range(3):
        for k in range(1, 3):
            k = (j + k) % 3
            dp[i + 1, j] = max(dp[i + 1, j], dp[i, k] + abc[k])
print(dp[-1].max())

Fixed submission:
n = int(input())
ABC = [list(map(int, input().split())) for i in range(n)]

# i日目にjを選択した後の幸福度 dp[i][j]
dp = [[0 for j in range(3)] for i in range(n + 1)]

for i in range(n):
    for j in range(3):
        for k in range(3):
            if j == k:
                continue
            dp[i + 1][k] = max(dp[i + 1][k], dp[i][j] + ABC[i][k])

print(max(dp[-1]))
Buggy python submission (verdict: Time Limit Exceeded):
import numpy as np

N, W = map(int, input().split())
dp = np.full((N + 1, W + 1), -np.inf, dtype=np.int64)
dp[0][0] = 0
for i in range(N):
    w, v = map(int, input().split())
    for j in range(W + 1):
        dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
        if j + w <= W:
            dp[i + 1][j + w] = max(dp[i + 1][j + w], dp[i][j] + v)
print(max(dp[-1]))


Fixed submission:
import numpy as np


n, capacity = map(int, input().split())
dp = np.zeros(capacity + 1, dtype=np.int64)
for _ in range(n):
    w, v = map(int, input().split())
    np.maximum(dp[:-w] + v, dp[w:], out=dp[w:])
print(dp[-1])

Buggy python submission (verdict: Time Limit Exceeded):
n, capacity = map(int, input().split())
dp = [0] * (capacity + 1)
for _ in range(n):
    w, v = map(int, input().split())
    for j in range(capacity, -1, -1):
        if j - w >= 0:
            dp[j] = max(dp[j], dp[j - w] + v)
print(dp[-1])

Fixed submission:
import numpy as np


n, capacity = map(int, input().split())
dp = np.zeros(capacity + 1, dtype=np.int64)
for _ in range(n):
    w, v = map(int, input().split())
    np.maximum(dp[:-w] + v, dp[w:], out=dp[w:])
print(dp[-1])
Buggy python submission (verdict: Time Limit Exceeded):
s = input()
t = input()
dp = [[0] * (len(t) + 1) for _ in range(len(s) + 1)]

for i in range(len(s)):
    for j in range(len(t)):
        if s[i] == t[j]:
            dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + 1)
        dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j + 1])
        dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i + 1][j])

i, j = len(s), len(t)
ans = ''
while i > 0 and j > 0:
    if dp[i][j] == dp[i - 1][j]:
        i -= 1
    elif dp[i][j] == dp[i][j - 1]:
        j -= 1
    else:
        ans += s[i - 1]
        i -= 1
        j -= 1
print(ans[::-1])

Fixed submission:
s = input()
t = input()
dp = [[0] * (len(t) + 1) for _ in range(len(s) + 1)]

for i in range(len(s)):
    for j in range(len(t)):
        if s[i] == t[j]:
            dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + 1)
        dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j + 1])
        dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i + 1][j])

i, j = len(s), len(t)
ans = ''
while i > 0 and j > 0:
    if dp[i][j] == dp[i - 1][j]:
        i -= 1
    elif dp[i][j] == dp[i][j - 1]:
        j -= 1
    else:
        ans += s[i - 1]
        i -= 1
        j -= 1
print(ans[::-1])
Buggy python submission (verdict: Runtime Error):
import sys


def input():
    return sys.stdin.readline().strip()


def dfs(v):
    if dp[v] >= 0:
        return dp[v]
    res = 0
    for nv in g[v]:
        res = max(res, dfs(nv) + 1)
    dp[v] = res
    return res


n, m = map(int, input().split())
g = {i: set() for i in range(1, n + 1)}
for _ in range(m):
    x, y = map(int, input().split())
    g[x].add(y)

dp = [-1] * (n + 1)
for v in g:
    dp[v] = max(dp[v], dfs(v))
print(max(dp))


Fixed submission:
import sys
sys.setrecursionlimit(10 ** 7)


def input():
    return sys.stdin.readline().strip()


def dfs(v):
    if dp[v] >= 0:
        return dp[v]
    res = 0
    for nv in g[v]:
        res = max(res, dfs(nv) + 1)
    dp[v] = res
    return res


n, m = map(int, input().split())
g = {i: set() for i in range(1, n + 1)}
for _ in range(m):
    x, y = map(int, input().split())
    g[x].add(y)

dp = [-1] * (n + 1)
for v in g:
    dp[v] = max(dp[v], dfs(v))
print(max(dp))

Buggy python submission (verdict: Runtime Error):
import sys


def input():
    return sys.stdin.readline().strip()


def dfs(v):
    if dp[v] >= 0:
        return dp[v]
    res = 0
    for nv in g[v]:
        res = max(res, dfs(nv) + 1)
    dp[v] = res
    return res


n, m = map(int, input().split())
g = {i: set() for i in range(1, n + 1)}
for _ in range(m):
    x, y = map(int, input().split())
    g[x].add(y)

dp = [-1] * (n + 1)
for v in g:
    dp[v] = max(dp[v], dfs(v))
    print(v, dp)

Fixed submission:
import sys
sys.setrecursionlimit(10 ** 7)


def input():
    return sys.stdin.readline().strip()


def dfs(v):
    if dp[v] >= 0:
        return dp[v]
    res = 0
    for nv in g[v]:
        res = max(res, dfs(nv) + 1)
    dp[v] = res
    return res


n, m = map(int, input().split())
g = {i: set() for i in range(1, n + 1)}
for _ in range(m):
    x, y = map(int, input().split())
    g[x].add(y)

dp = [-1] * (n + 1)
for v in g:
    dp[v] = max(dp[v], dfs(v))
print(max(dp))

Buggy python submission (verdict: Runtime Error):
import sys


def input():
    return sys.stdin.readline().strip()


def dfs(v):
    if dp[v] > 0:
        return dp[v]
    res = 0
    for nv in g[v]:
        res = max(res, dfs(nv) + 1)
    dp[v] = res
    return res


n, m = map(int, input().split())
g = {i: set() for i in range(1, n + 1)}
for _ in range(m):
    x, y = map(int, input().split())
    g[x].add(y)

dp = [-1] * (n + 1)
for v in g:
    dp[v] = max(dp[v], dfs(v))
    print(v, dp)

Fixed submission:
import sys
sys.setrecursionlimit(10 ** 7)


def input():
    return sys.stdin.readline().strip()


def dfs(v):
    if dp[v] >= 0:
        return dp[v]
    res = 0
    for nv in g[v]:
        res = max(res, dfs(nv) + 1)
    dp[v] = res
    return res


n, m = map(int, input().split())
g = {i: set() for i in range(1, n + 1)}
for _ in range(m):
    x, y = map(int, input().split())
    g[x].add(y)

dp = [-1] * (n + 1)
for v in g:
    dp[v] = max(dp[v], dfs(v))
print(max(dp))
Buggy python submission (verdict: Runtime Error):
from fractions import gcd


N, M = map(int, input().split())
S = input()
T = input()
LCM = N * M // gcd(N, M)
S_dist = [""] * LCM
T_dist = [""] * LCM
for i in range(N):
    S_dist[i * LCM // N] = S[i]
for i in range(M):
    T_dist[i * LCM // M] = T[i]
for s, t in zip(S_dist, T_dist):
    if s != "" and t != "" and s != t:
        print(-1)
        break
else:
    print(LCM)


Fixed submission:
from fractions import gcd


N, M = map(int, input().split())
S = input()
T = input()
g = gcd(N, M)
N //= g
M //= g
for i in range(g):
    if S[i * N] != T[i * M]:
        print(-1)
        break
else:
    print(N * M * g)
Buggy python submission (verdict: Runtime Error):
N, M = map(int, input().split())
ans = 0
for i in range(1, (M + N - 2) // (N - 1)):
    if (M - i * (N - 1)) % i == 0:
        ans = i
print(ans)


Fixed submission:
def enum_divisors(n):
    res = []
    for i in range(1, int(n ** 0.5) + 1):
        if n % i == 0:
            res.append(i)
            if i != n // i:
                res.append(n // i)
    return res


N, M = map(int, input().split())
divs = filter(lambda x: x <= M // N, enum_divisors(M))
print(max(divs))
Buggy python submission (verdict: Time Limit Exceeded):
S = input()
T = input()
N = len(S)
pos_S = {c: set() for c in "abcdefghijklmnopqrstuvwxyz"}
[pos_S[S[i]].add(i) for i in range(N)]
pos_T = {c: set() for c in "abcdefghijklmnopqrstuvwxyz"}
[pos_T[T[i]].add(i) for i in range(N)]
if all(pos_S[S[i]] == pos_T[T[i]] for i in range(N)):
    print("Yes")
else:
    print("No")


Fixed submission:
from collections import Counter


S = Counter(input())
T = Counter(input())
if sorted(S.values()) == sorted(T.values()):
    print("Yes")
else:
    print("No")

Buggy python submission (verdict: Time Limit Exceeded):
S = input()
T = input()
N = len(S)
pos_S = {c: [] for c in "abcdefghijklmnopqrstuvwxyz"}
[pos_S[S[i]].append(i) for i in range(N)]
pos_T = {c: [] for c in "abcdefghijklmnopqrstuvwxyz"}
[pos_T[T[i]].append(i) for i in range(N)]
if all(pos_S[S[i]] == pos_T[T[i]] for i in range(N)):
    print("Yes")
else:
    print("No")


Fixed submission:
from collections import Counter


S = Counter(input())
T = Counter(input())
if sorted(S.values()) == sorted(T.values()):
    print("Yes")
else:
    print("No")
Buggy python submission (verdict: Runtime Error):
import sys
from functools import lru_cache


sys.setrecursionlimit(100000)


@lru_cache(maxsize=None)
def rec(n):
    if n == 0:
        return 0
    res = n
    i = 1
    while i <= n:
        res = min(res, rec(n - i) + 1)
        i *= 6
    i = 9
    while i <= n:
        res = min(res, rec(n - i) + 1)
        i *= 9
    return res


N = int(input())
print(rec(N))




Fixed submission:
N = int(input())
dp = [N] * (N + 1)
dp[0] = 0
for i in range(N):
    j = 1
    while i + j <= N:
        dp[i + j] = min(dp[i + j], dp[i] + 1)
        j *= 6
    j = 9
    while i + j <= N:
        dp[i + j] = min(dp[i + j], dp[i] + 1)
        j *= 9
print(dp[-1])
Buggy python submission (verdict: Time Limit Exceeded):
from itertools import permutations


N, C = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
cost = [[0] * 3 for _ in range(C)]

for i in range(N):
    for j in range(N):
        for k in range(C):
            cost[k][(i + j) % 3] += D[c[i][j] - 1][k]


ans = min(
    sum(cost[c][i] for i, c in enumerate(colors))
    for colors in permutations(range(C), 3)
)
print(ans)


Fixed submission:
from itertools import permutations


N, C = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
cost = [[0] * 3 for _ in range(C)]

for i in range(N):
    for j in range(N):
        for k in range(C):
            cost[k][(i + j) % 3] += D[c[i][j] - 1][k]

ans = min(
    sum(cost[c][i] for i, c in enumerate(colors))
    for colors in permutations(range(C), 3)
)
print(ans)

Buggy python submission (verdict: Time Limit Exceeded):
from itertools import combinations, permutations


N, C = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]

ans = float("inf")
for colors in combinations(range(C), 3):
    for p_colors in permutations(colors):
        tmp = 0
        for i in range(N):
            for j in range(N):
                c_color = c[i][j] - 1
                n_color = p_colors[(i + j) % 3]
                if c_color == n_color:
                    continue
                tmp += D[c_color][n_color]
        ans = min(ans, tmp)
print(ans)


Fixed submission:
from itertools import permutations


N, C = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]
cost = [[0] * 3 for _ in range(C)]

for i in range(N):
    for j in range(N):
        for k in range(C):
            cost[k][(i + j) % 3] += D[c[i][j] - 1][k]

ans = min(
    sum(cost[c][i] for i, c in enumerate(colors))
    for colors in permutations(range(C), 3)
)
print(ans)