alexjercan/bugnet huggingface dataset:
Problem p03408 (Python) — buggy submission, verdict: Runtime Error

# ABC091B

n = int(input())
s = [0] * n
for i in range(n):
    s[i] = input()
m = int(input())
t = [0] * m
for i in range(m):
    t[i] = input()

blue = {}
for c in s:
    if c in blue.keys():
        blue[c] += 1
    else:
        blue.setdefault(c, 1)
red = {}
for c in t:
    if c in red.keys():
        red[c] += 1
    else:
        red.setdefault(c, 1)

Max = 0
for blue_key, blue_value in blue.items():
    get = blue_value
    if blue_key in red.keys():
        for red_key, red_value in red.items():
            if blue_key == red_key:
                get -= red_value
                break
    Max = max(Max, get)
print(Max)


Error: TypeError: int() argument must be a string, a bytes-like object or a real number, not 'builtin_function_or_method'
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03408/Python/s487565189.py", line 3, in <module>
    n = int(input)
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'builtin_function_or_method'


Fixed submission:

# ABC091B

n = int(input)
s = [0] * n
for i in range(n):
    s[i] = input()
m = int(input)
t = [0] * m
for i in range(m):
    t[i] = input()

blue = {}
for c in s:
    if c in blue.keys():
        blue[c] += 1
    else:
        blue.setdefault(c, 1)
red = {}
for c in t:
    if c in red.keys():
        red[c] += 1
    else:
        red.setdefault(c, 1)

Max = 0
for blue_key, blue_value in blue.items():
    get = blue_value
    if blue_key in red.keys():
        for red_key, red_value in red.items():
            if blue_key == red_key:
                get -= red_value
                break
    Max = max(Max, get)
print(Max)
Problem p03408 (Python) — buggy submission, verdict: Runtime Error

import sys

sys.setrecursionlimit(4100000)


def inputs(num_of_input):
    ins = [input() for i in range(num_of_input)]
    return ins


def solve(blues, reds):
    blue_counts = {}
    red_counts = {}

    for b in blues:
        if b not in blue_counts:
            blue_counts[b] = 1
        else:
            blue_counts[b] += 1

    for r in reds:
        if r not in red_counts:
            red_counts[r] = 1
        else:
            red_counts[r] += 1

    max_count = 0
    for name, c in blue_counts.items():
        if name in red_counts:
            max_count = max(max_count, c - red_counts[name])
        else:
            max_count = max(max_count, c)
    return max_count


def string_to_int(string):
    return list(map(lambda x: int(x), string.split()))


if __name__ == "__main__":
    [N] = string_to_int(input())
    blues = inputs(N)
    [M] = string_to_int(input())
    reds = inputs(M)
    ret = solve(blues, reds)
    print(ret)


Error: TypeError: inputs() missing 1 required positional argument: 'num_of_input'
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03408/Python/s858924667.py", line 41, in <module>
    [N] = string_to_int(inputs())
TypeError: inputs() missing 1 required positional argument: 'num_of_input'


Fixed submission:

import sys

sys.setrecursionlimit(4100000)


def inputs(num_of_input):
    ins = [input() for i in range(num_of_input)]
    return ins


def solve(blues, reds):
    blue_counts = {}
    red_counts = {}

    for b in blues:
        if b not in blue_counts:
            blue_counts[b] = 1
        else:
            blue_counts[b] += 1

    for r in reds:
        if r not in red_counts:
            red_counts[r] = 1
        else:
            red_counts[r] += 1

    max_count = 0
    for name, c in blue_counts.items():
        if name in red_counts:
            max_count = max(max_count, c - red_counts[name])
        else:
            max_count = max(max_count, c)
    return max_count


def string_to_int(string):
    return list(map(lambda x: int(x), string.split()))


if __name__ == "__main__":
    [N] = string_to_int(inputs())
    blues = inputs(N)
    [M] = string_to_int(inputs())
    reds = inputs(M)
    ret = solve(blues, reds)
    print(ret)
Problem p03408 (Python) — buggy submission, verdict: Runtime Error

from collections import Counter

N = int(input())
S = [input() for _ in range(N)]

M = int(input())
T = [input() for _ in range(M)]

s_counter = Counter(S)
t_counter = Counter(T)

result = 0

for k, v in s_counter.items():
    result = max(result, v - (t_counter[k] if t_counter[k] else 0))

print(result if result > 0 else 0)


Error: ValueError: too many values to unpack (expected 2)
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03408/Python/s472001842.py", line 14, in <module>
    for k, v in s_counter:
ValueError: too many values to unpack (expected 2)


Fixed submission:

from collections import Counter

N = int(input())
S = [input() for _ in range(N)]

M = int(input())
T = [input() for _ in range(M)]

s_counter = Counter(S)
t_counter = Counter(T)

result = 0

for k, v in s_counter:
    result = max(result, v - (t_counter[k] if t_counter[k] else 0))

print(result)
Problem p03408 (Python) — buggy submission, verdict: Runtime Error

from collections import defaultdict

n = int(input())
d = defaultdict(int)
for _ in range(n):
    s = input()
    d[s] += 1
m = int(input())
for _ in range(m):
    s = input()
    d[s] -= 1

answer = sorted([d[k] for k in d.keys()])[-1]
if answer < 0:
    answer = 0
print(answer)


Error: KeyError: 'apple'
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03408/Python/s279183282.py", line 7, in <module>
    d[s] += 1
KeyError: 'apple'


Fixed submission:

from collections import defaultdict

n = int(input())
d = defaultdict()
for _ in range(n):
    s = input()
    d[s] += 1
m = int(input())
for _ in range(m):
    s = input()
    d[s] -= 1

answer = sorted([d[k] for k in d.keys()])[-1]
if answer < 0:
    answer = 0
print(answer)
Problem p03408 (Python) — buggy submission, verdict: Runtime Error

def main(n, s: list, m, t: list):
    choices = set(s + t)

    ans = [0]

    for choice in choices:
        ans_t = 0
        for _s in s:
            if choice == _s:
                ans_t += 1
        for _t in t:
            if choice == _t:
                ans_t -= 1

        ans.append(ans_t)

    print(max(ans))


if __name__ == "__main__":
    n = int(input())
    s = [input() for _ in range(n)]
    m = int(input())
    t = [input() for _ in range(m)]

    main(n, s, m, t)


Error: EOFError: EOF when reading a line
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03408/Python/s871878822.py", line 24, in <module>
    t = [input() for _ in range(n)]
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03408/Python/s871878822.py", line 24, in <listcomp>
    t = [input() for _ in range(n)]
EOFError: EOF when reading a line


Fixed submission:

def main(n, s: list, m, t: list):
    choices = set(s + t)

    ans = [0]

    for choice in choices:
        ans_t = 0
        for _s in s:
            if choice == _s:
                ans_t += 1
        for _t in t:
            if choice == _t:
                ans_t -= 1

        ans.append(ans_t)

    print(max(ans))


if __name__ == "__main__":
    n = int(input())
    s = [input() for _ in range(n)]
    m = int(input())
    t = [input() for _ in range(n)]

    main(n, s, m, t)
Problem p03409 (Python) — buggy submission, verdict: Time Limit Exceeded

def main():
    N = int(input())
    red = sorted(
        [list(map(int, input().split())) for _ in range(N)],
        key=lambda x: x[1],
        reverse=True,
    )
    blue = sorted(
        [list(map(int, input().split())) for _ in range(N)], key=lambda x: x[0]
    )
    ans = 0
    for b in blue:
        for i, r in enumerate(red):
            if b[0] > r[0] and b[1] > r[1]:
                ans += 1
                red.pop(i)
                break
    print(ans)


main()


Error: TLE

Fixed submission:

def f(blue, red, ans):
    c = 0
    for i, b in enumerate(blue):
        for j, r in enumerate(red):
            if b[0] >= r[0] and b[1] >= r[1]:
                blue.pop(i)
                red.pop(j)
                c = max(c, f(blue, red, ans + 1))
                blue.insert(i, b)
                red.insert(j, r)
    return max(c, ans)


def main():
    N = int(input())
    red = [list(map(int, input().split())) for _ in range(N)]
    blue = [list(map(int, input().split())) for _ in range(N)]
    print(f(blue, red, 0))


main()
Problem p03409 (Python) — buggy submission, verdict: Runtime Error

N = int(input())

red_points = [[int(i) for i in input().split()] for j in range(N)]

blue_points = [[int(i) for i in input().split()] for j in range(N)]

red_points.sort()
blue_points.sort()
count = 0
distance = 9999
for blue_point in blue_points:
    tmp = [i for i in red_points if blue_point[0] > i[0] and blue_point[1] > i[1]]
    if tmp:
        for j in tmp:
            if (blue_point[1] - j[1]) < distance:
                distance = blue_point[1] - j[1]
                min_red = j
        count = count + 1
        red_points.remove(min_red)
        distance = 9999

print(count)


Error: NameError: name 'tmp' is not defined
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03409/Python/s895373765.py", line 17, in <module>
    if tmp in red_points:
NameError: name 'tmp' is not defined


Fixed submission:

N = int(input())

red_points = [[int(i) for i in input().split()] for j in range(N)]

blue_points = [[int(i) for i in input().split()] for j in range(N)]

red_points.sort()
blue_points.sort()
count = 0
distance = 9999
for blue_point in blue_points:
    for red_point in red_points:
        if (blue_point[0] > red_point[0]) and (blue_point[1] > red_point[1]):
            if blue_point[1] - red_point[1] < distance:
                distance = blue_point[1] - red_point[1]
                tmp = red_point
    if tmp in red_points:
        red_points.remove(tmp)
        tmp.clear()
        count = count + 1
    distance = 9999
print(count)
Problem p03416 (Python) — buggy submission, verdict: Runtime Error

a, b = map(int, input().split())

res = 0
for i in range(a, b + 1):
    i_str = str(i)
    if i_str == i_str[::-1]:
        res += 1
print(res)


Error: ValueError: too many values to unpack (expected 2)
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03416/Python/s354471054.py", line 1, in <module>
    a, b = map(int, input())
ValueError: too many values to unpack (expected 2)


Fixed submission:

a, b = map(int, input())

res = 0
for i in range(a, b + 1):
    i_str = str(i)
    if i_str == i_str[::-1]:
        res += 1
print(res)
Problem p03419 (Python) — buggy submission, verdict: Time Limit Exceeded

N, M = list(map(int, input().split()))
result = 0
if N == 1 and M == 1:
    result = 1
elif N == 1:
    result = M - 2
elif M == 1:
    result = N - 2
else:
    result = (N - 2) * (M - 2)
print(result)


Error: TLE

Fixed submission:

N, M = list(map(int, input().split()))
result = 0
pos = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1)]
for i in range(N):
    for j in range(M):
        num = 0
        for p in pos:
            i_dest = i + p[0]
            j_dest = j + p[1]
            if 0 <= i_dest < N and 0 <= j_dest < M:
                num += 1
        if num % 2 != 0:
            result += 1
print(result)
Problem p03420 (Python) — buggy submission, verdict: Time Limit Exceeded

import numpy as np

n, k = map(int, input().split())
ans = 0
for m in range(k, n):
    nm = n - m
    sb = m + 1
    s = nm // sb
    p = s + 1 if m else s
    ps = sb
    for d in range(s, 0, -1):
        ds = nm // d + 1
        co = ds - ps
        ans += co * p
        ps = ds
        p -= 1
    ans += n + 1 - ps

    # ds = [nm // d + 1 for d in range(s, 0, -1)]
    # ds = [sb] + ds + [n + 1]
    # # print(m, nm, sb, s, ds)
    # dd = np.diff(ds)
    # pd = np.arange(s + 1, 0, -1) if m else np.arange(s, -1, -1)
    # # print(dd, pd, dd * pd, sum(dd * pd))
    # ans += sum(dd * pd)
print(ans)


Error: TLE

Fixed submission:

import numpy as np

n, k = map(int, input().split())
ans = 0
for m in range(k, n):
    nm = n - m
    sb = m + 1
    s = nm // sb
    ds = [nm // d + 1 for d in range(s, 0, -1)]
    ds = [sb] + ds + [n + 1]
    # print(m, nm, sb, s, ds)
    dd = np.diff(ds)
    pd = np.arange(s + 1, 0, -1) if m else np.arange(s, -1, -1)
    # print(dd, pd, dd * pd, sum(dd * pd))
    ans += sum(dd * pd)
print(ans)
Problem p03424 (Python) — buggy submission, verdict: Runtime Error

N = int(input())
S = list(map(str, input().split()))

if "Y" in S:
    print("Four")
else:
    print("Three")


Error: ValueError: invalid literal for int() with base 10: 'G'
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03424/Python/s702937056.py", line 2, in <module>
    S = list(map(int, input().split()))
ValueError: invalid literal for int() with base 10: 'G'


Fixed submission:

N = int(input())
S = list(map(int, input().split()))

if "Y" in S:
    print("Four")
else:
    print("Three")
Problem p03424 (Python) — buggy submission, verdict: Runtime Error

n = int(input())
s = list(input().split())

print("Four" if "Y" in s else "Three")


Error: ValueError: invalid literal for int() with base 10: 'G'
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03424/Python/s597514940.py", line 2, in <module>
    s = list(map(int, input().split()))
ValueError: invalid literal for int() with base 10: 'G'


Fixed submission:

n = int(input())
s = list(map(int, input().split()))

print("Four" if "Y" in s else "Three")
Problem p03424 (Python) — buggy submission, verdict: Runtime Error

# -*- coding: utf-8 -*-


def main():
    """Function."""
    n = int(input())
    s = list(map(str, input().split()))

    check = set()
    for i in range(n):
        check.add(s[i])

    if len(check) == 3:
        print("Three")
    else:
        print("Four")


if __name__ == "__main__":
    main()


Error: AttributeError: 'set' object has no attribute 'append'
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03424/Python/s300014166.py", line 20, in <module>
    main()
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03424/Python/s300014166.py", line 11, in main
    check.append(s[i])
AttributeError: 'set' object has no attribute 'append'


Fixed submission:

# -*- coding: utf-8 -*-


def main():
    """Function."""
    n = int(input())
    s = list(map(str, input().split()))

    check = set()
    for i in range(n):
        check.append(s[i])

    if len(check) == 3:
        print("Three")
    else:
        print("Four")


if __name__ == "__main__":
    main()
Problem p03424 (Python) — buggy submission, verdict: Runtime Error

N = int(input())
s = list(map(str, input().split()))
print(["Four", "Three"][len(set(s)) == 3])


Error: TypeError: map() must have at least two arguments.
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03424/Python/s362939003.py", line 2, in <module>
    s = list(map(input().split()))
TypeError: map() must have at least two arguments.


Fixed submission:

N = int(input())
s = list(map(input().split()))
print(len(set(s)))
Problem p03425 (Python) — buggy submission, verdict: Runtime Error

import itertools

N = int(input())
S = [input() for _ in range(N)]

cnt = [0 for _ in range(5)]
for s in S:
    if s[0] == "M":
        cnt[0] += 1
    elif s[0] == "A":
        cnt[1] += 1
    elif s[0] == "R":
        cnt[2] += 1
    elif s[0] == "C":
        cnt[3] += 1
    elif s[0] == "H":
        cnt[4] += 1

ans = 0
for i, j, k in itertools.combinations(cnt, r=3):
    ans += i * j * k

print(ans)


Error: WA

Fixed submission:

import itertools

N = int(input())
S = [input() for _ in range(N)]

cnt = [0 for _ in range(5)]
for s in S:
    if s[0] == "M":
        cnt[0] += 1
    elif s[1] == "A":
        cnt[1] += 1
    elif s[2] == "R":
        cnt[2] += 1
    elif s[3] == "C":
        cnt[3] += 1
    elif s[4] == "H":
        cnt[4] += 1

ans = 0
for i, j, k in itertools.permutations(cnt, r=3):
    ans += i * j * k

print(ans)
Problem p03425 (Python) — buggy submission, verdict: Time Limit Exceeded

N = int(input())
cnt_li = [0, 0, 0, 0, 0]
comb = [
    [0, 1, 2],
    [0, 1, 3],
    [0, 1, 4],
    [0, 2, 3],
    [0, 2, 4],
    [0, 3, 4],
    [1, 2, 3],
    [1, 2, 4],
    [1, 3, 4],
    [2, 3, 4],
]
for _ in range(N):
    s = input()
    if s[0] == "M":
        cnt_li[0] += 1
    if s[0] == "A":
        cnt_li[1] += 1
    if s[0] == "R":
        cnt_li[2] += 1
    if s[0] == "C":
        cnt_li[3] += 1
    if s[0] == "H":
        cnt_li[4] += 1
ans = 0
for i in range(len(comb)):
    one, two, three = comb[i]
    mid = cnt_li[one] * cnt_li[two] * cnt_li[three]
    ans += mid
print(ans)


Error: TLE

Fixed submission:

from itertools import combinations

N = int(input())
s_li = []
for _ in range(N):
    s = input()
    if s[0] in "MARCH":
        s_li.append(s)
s_set = set(s_li)
# print(len(list(combinations(s_set, 3))))
ans = 0
for c in combinations(s_set, 3):
    initial = []
    for name in c:
        if name[0] in initial:
            break
        initial.append(name[0])
    else:
        ans += 1
print(ans)
Problem p03425 (Python) — buggy submission, verdict: Time Limit Exceeded

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from itertools import combinations


def main():

    N = int(input())

    count = {x: 0 for x in "MARCH"}

    for _ in range(N):
        s = input()[0]
        if s in count:
            count[s] += 1

    result = 0
    for a, b, c in combinations("MARCH", 3):
        result += count[a] * count[b] * count[c]

    print(result)


if __name__ == "__main__":
    main()


Error: TLE

Fixed submission:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import itertools


def main():
    N = int(input())
    S = [input() for _ in range(N)]

    march = []
    for s in S:
        if s[0] in ["M", "A", "R", "C", "H"]:
            march.append(s[0])

    result = []
    for comb in list(itertools.combinations(march, 3)):
        if comb[0] != comb[1] and comb[0] != comb[2] and comb[1] != comb[2]:
            result.append(comb)

    print(len(result))


if __name__ == "__main__":
    main()
Problem p03425 (Python) — buggy submission, verdict: Time Limit Exceeded

import itertools

n = int(input())
ls = [input()[:1] for _ in range(n)]
ans = 0
cmb = list(itertools.combinations(list("MARCH"), 3))

for c in cmb:
    ans += ls.count(c[0]) * ls.count(c[1]) * ls.count(c[2])

print(ans)


Error: TLE

Fixed submission:

import re
import itertools

n = int(input())
ls = [input() for _ in range(n)]
new_ls = []
ans = 0

for name in ls:
    if re.match(r"[MARCH]", name):
        new_ls.append(name[:1])

comb_ls = list(itertools.combinations(new_ls, 3))


if new_ls:
    for comb in comb_ls:
        s = set(comb)
        if len(s) == 3:
            ans += 1
    print(ans)
else:
    print(0)
    quit()
Problem p03426 (Python) — buggy submission, verdict: Time Limit Exceeded

def main():
    H, W, D = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(H)]
    Q = int(input())
    ans = []

    x = [0 for _ in range(90001)]
    y = [0 for _ in range(90001)]
    dp = [0 for _ in range(90001)]

    for i, row in enumerate(A):
        for j, a in enumerate(row):
            x[a] = j
            y[a] = i
    for i in range(D + 1, H * W + 1):
        dp[i] = dp[i - D] + abs(x[i] - x[i - D]) + abs(y[i] - y[i - D])

    for _ in range(Q):
        L, R = map(int, input().split())
        ans.append(dp[R] - dp[L])
    for a in ans:
        print(a)


main()


Error: TLE

Fixed submission:

def main():
    H, W, D = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(H)]
    Q = int(input())
    ans = []

    x = [0 for _ in range(90001)]
    y = [0 for _ in range(90001)]
    for i, row in enumerate(A):
        for j, a in enumerate(row):
            x[a] = j
            y[a] = i

    for _ in range(Q):
        L, R = map(int, input().split())
        if L == R:
            ans.append(0)
            continue
        m = 0
        while L != R:
            m += abs(x[L] - x[L + D]) + abs(y[L] - y[L + D])
            L += D
        ans.append(m)
    for a in ans:
        print(a)


main()
Problem p03426 (Python) — buggy submission, verdict: Time Limit Exceeded

H, W, D = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]

d = [None for _ in range(H * W + 1)]
for i in range(H):
    for j in range(W):
        d[A[i][j]] = (i, j)

cumsum = [0 for _ in range(H * W + 1)]
for m in range(1, D + 1):
    i = m
    while i <= H * W:
        if i - D <= 0:
            i += D
            continue
        x1, y1 = d[i - D]
        x2, y2 = d[i]
        dist = abs(x2 - x1) + abs(y2 - y1)
        cumsum[i] = cumsum[i - D] + dist
        i += D

Q = int(input())
LR = [tuple(map(int, input().split())) for _ in range(Q)]
for L, R in LR:
    print(cumsum[R] - cumsum[L])


Error: TLE

Fixed submission:

H, W, D = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]
d = dict()
for i in range(H):
    for j in range(W):
        d[A[i][j]] = (i, j)
Q = int(input())
LR = [tuple(map(int, input().split())) for _ in range(Q)]
for L, R in LR:
    pow = 0
    while L != R:
        i, j = d[L]
        L += D
        x, y = d[L]
        pow += abs(x - i) + abs(y - j)
    print(pow)
Problem p03426 (Python) — buggy submission, verdict: Time Limit Exceeded

h, w, d = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(h)]

nc = dict()
for row in range(h):
    for col in range(w):
        v = A[row][col]
        nc[v] = (row, col)

q = int(input())
lrs = [list(map(int, input().split())) for _ in range(q)]

c_sums = [[0] for _ in range(d)]
for r in range(d):
    k = 0
    if r == 0:
        k = 1
    while r + (k + 1) * d <= h * w:
        i, j = nc[r + k * d]
        x, y = nc[r + (k + 1) * d]
        t = c_sums[r][-1] + abs(x - i) + abs(y - j)
        c_sums[r].append(t)
        k += 1

for lr in lrs:
    l, r = lr
    ld, rest = divmod(l, d)
    rd = r // d
    if rest == 0:
        ld -= 1
        rd -= 1
    print(c_sums[rest][rd] - c_sums[rest][ld])


Error: TLE

Fixed submission:

h, w, d = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(h)]

nc = dict()
for row in range(h):
    for col in range(w):
        v = A[row][col]
        nc[v] = (row, col)

q = int(input())
lrs = [list(map(int, input().split())) for _ in range(q)]

for lr in lrs:
    l, r = lr
    ans = 0
    while l != r:
        i, j = nc[l]
        x, y = nc[l + d]
        ans += abs(x - i) + abs(y - j)
        l += d
    print(ans)
Problem p03426 (Python) — buggy submission, verdict: Time Limit Exceeded

h, w, d = map(int, input().split())

p = [[] for _ in range(h * w)]

for i in range(h):
    temp = list(map(int, input().split()))
    for j in range(w):
        p[temp[j] - 1] = [i, j]

q = int(input())
a = [[int(x) - 1 for x in input().split()] for _ in range(q)]

s = [0 for _ in range(h * w)]
for i in range(d, h * w):
    s[i] = s[i - d] + abs(p[i][0] - p[i - d][0]) + abs(p[i][1] - p[i - d][1])

for i in range(q):
    print(s[a[i][1]] - s[a[i][0]])


Error: TLE

Fixed submission:

h, w, d = map(int, input().split())

p = [[] for _ in range(h * w)]

for i in range(h):
    temp = list(map(int, input().split()))
    for j in range(w):
        p[temp[j] - 1] = [i, j]

q = int(input())
a = [[int(x) - 1 for x in input().split()] for _ in range(q)]

for i in range(q):
    temp = 0
    j = a[i][1]
    while j > a[i][0]:
        temp += abs(p[j][0] - p[j - d][0]) + abs(p[j][1] - p[j - d][1])
        j -= d
    print(temp)