Harryxun/GPT-100-sft-dataset huggingface dataset:
Problem p03426 (python)

Fixed submission:
import sys
input = sys.stdin.buffer.readline

def main():
    H,W,D = map(int,input().split())
    A = [list(map(int,input().split())) for _ in range(H)]
    Q = int(input())
    test = [list(map(int,input().split())) for _ in range(Q)]
    
    at = [None for _ in range(H*W)]
    for x in range(H):
        for y in range(W):
            at[A[x][y]-1] = (x,y)
            
    def move(x,y):
        dx = abs(at[y][0]-at[x][0])
        dy = abs(at[y][1]-at[x][1])
        return dx + dy
            
    cost = [[0 for _ in range(-(-H*W//D))] for _ in range(D)]
    for i in range(D):
        do = -(-(H*W-i)//D)
        for j in range(do-1):
            cost[i][j+1] = cost[i][j] + move(D*j+i,D*(j+1)+i)
            
    for i in range(Q):
        start,goal = test[i]
        v = start % D - 1
        u = -(-start // D) - 1
        w = -(-goal // D) - 1
        print(cost[v][w]-cost[v][u])
    
if __name__ == "__main__":
    main()

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.buffer.readline

def main():
    H,W,D = map(int,input().split())
    a = [list(map(int,input().split())) for _ in range(H)]
    pos = [[-1,-1] for _ in range(H*W)]
    for i in range(H):
        for j in range(W):
            pos[a[i][j]-1][0] = i
            pos[a[i][j]-1][1] = j
    
    def manhattan_dist(x1,y1,x2,y2):
        return abs(x2-x1)+abs(y2-y1)

    ans_list = [[0] for _ in range(D)]
    for i in range(D):
        do = -(-(H*W-i)//D)
        for j in range(do-1):
            x1,y1 = pos[D*j+i]
            x2,y2 = pos[D*(j+1)+i]
            md = manhattan_dist(x1,y1,x2,y2)
            ans_list[i].append(ans_list[i][-1]+md)
    
    Q = int(input())
    for _ in range(Q):
        a,b = map(int,input().split())
        mod = (a-1)%D
        print(ans_list[mod][(b-mod)//D]-ans_list[mod][(a-mod)//D])

if __name__ == "__main__":
    main()

Buggy submission (verdict: Runtime Error):
import sys
input = sys.stdin.buffer.readline

def main():
    H,W,D = map(int,input().split())
    a = [list(map(int,input().split())) for _ in range(H)]
    pos = [[-1,-1] for _ in range(H*W)]
    for i in range(H):
        for j in range(W):
            pos[a[i][j]-1][0] = i
            pos[a[i][j]-1][1] = j
    
    def manhattan_dist(x1,y1,x2,y2):
        return abs(x2-x1)+abs(y2-y1)

    ans_list = [[0] for _ in range(D)]
    for i in range(D):
        for j in range((H*W-i-1)//D):
            x1,y1 = pos[D*j+i]
            x2,y2 = pos[D*(j+1)+i]
            md = manhattan_dist(x1,y1,x2,y2)
            ans_list[i].append(ans_list[i][-1]+md)
    
    Q = int(input())
    for _ in range(Q):
        a,b = map(int,input().split())
        mod = (a-1)%D
        print(ans_list[mod][(b-mod)//D]-ans_list[mod][(a-mod)//D])

if __name__ == "__main__":
    main()
Problem p02580 (python)

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

import numpy
from collections import defaultdict

def main():
  h, w, m = map(int, input().strip().split())
  fieldh = numpy.zeros(h, dtype=numpy.int)
  fieldw = numpy.zeros(w, dtype=numpy.int)
  field = defaultdict(int)
  for _ in range(m):
    ih, iw = map(int, input().strip().split())
    fieldh[ih-1] += 1
    fieldw[iw-1] += 1
    field[ih-1, iw-1] = 1
    
  max_h = numpy.max(fieldh)
  max_w = numpy.max(fieldw)
  argsort_h = [ ih for ih in range(h) if fieldh[ih] == max_h ]
  argsort_w = [ iw for iw in range(w) if fieldw[iw] == max_w ]
  
  max_cnt = 0
  for ih in argsort_h:
    for iw in argsort_w:
      if field[ih, iw] == 0:
        max_cnt = max(max_cnt, fieldh[ih]+fieldw[iw])
        print(max_cnt)
        return 
      else:
        max_cnt = max(max_cnt, fieldh[ih]+fieldw[iw]-1)
  print(max_cnt)

if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/python3
# -*- coding:utf-8 -*-

import numpy

def main():
  h, w, m = map(int, input().strip().split())
  fieldh = numpy.zeros(h, dtype=numpy.int)
  fieldw = numpy.zeros(w, dtype=numpy.int)
  field = numpy.zeros((h, w), dtype=numpy.int)
  for _ in range(m):
    ih, iw = map(int, input().strip().split())
    fieldh[ih-1] += 1
    fieldw[iw-1] += 1
    field[ih-1, iw-1] = 1
    
  max_h = numpy.max(fieldh)
  max_w = numpy.max(fieldw)
  argsort_h = [ ih for ih in range(h) if fieldh[ih] == max_h ]
  argsort_w = [ iw for iw in range(w) if fieldw[iw] == max_w ]
  
  max_cnt = 0
  for ih in argsort_h:
    for iw in argsort_w:
      if field[ih, iw] == 0:
        max_cnt = max(max_cnt, fieldh[ih]+fieldw[iw])
        print(max_cnt)
        return 
      else:
        max_cnt = max(max_cnt, fieldh[ih]+fieldw[iw]-1)
  print(max_cnt)

if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/python3
# -*- coding:utf-8 -*-

import numpy

def main():
  h, w, m = map(int, input().strip().split())
  fieldh = numpy.zeros(h, dtype=numpy.int)
  fieldw = numpy.zeros(w, dtype=numpy.int)
  field = numpy.zeros((h, w), dtype=numpy.int)
  for _ in range(m):
    ih, iw = map(int, input().strip().split())
    fieldh[ih-1] += 1
    fieldw[iw-1] += 1
    field[ih-1, iw-1] = 1
  max_h = numpy.max(fieldh)
  max_w = numpy.max(fieldw)
  argsort_h = fieldh.argsort()[::-1]
  argsort_w = fieldw.argsort()[::-1]
  
  max_cnt = 0
  for ih in argsort_h:
    for iw in argsort_w:
      if field[ih, iw] == 0:
        max_cnt = max(max_cnt, fieldh[ih]+fieldw[iw])
        print(max_cnt)
        return 
      else:
        max_cnt = max(max_cnt, fieldh[ih]+fieldw[iw]-1)

if __name__=='__main__':
  main()
Problem p02625 (python)

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

def p(n, k, mod):
  x = 1
  for ik in range(k):
    x *= (n - ik)
    x %= mod
  return x

MAX = 10 ** 9 + 7
def main():
  n, m = map(int, input().strip().split())
  s = 0
  nck = 1
  mpk = 1
  mkpnk = p(m, n, MAX)
  for k in range(0, n+1):
    if 0 < k <= n:
      nck *= (n - (k-1)) * pow(k, MAX-2, MAX) 
      nck %= MAX
    if 0 < k <= m:
      mpk *= (m - (k-1))
      mpk %= MAX
    if 0 < k <= n:
      mkpnk *= pow(m - (k - 1), MAX-2, MAX) 
      mkpnk %= MAX
    s += nck * ( (-1) ** k) * mpk * (mkpnk) ** 2
    s %= MAX
  print(s)
  

if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
%%writefile e.py
#!/usr/bin/python3
# -*- coding:utf-8 -*-

def p(n, k, mod):
  x = 1
  for ik in range(k):
    x *= (n - ik)
    x %= mod
  return x

MAX = 10 ** 9 + 7
def main():
  n, m = map(int, input().strip().split())
  s = 0
  nck = 1
  mpk = 1
  mkpnk = p(m, n, MAX)
  for k in range(0, n+1):
    if 0 < k <= n:
      nck *= (n - (k-1)) * pow(k, MAX-2, MAX) 
      nck %= MAX
    if 0 < k <= m:
      mpk *= (m - (k-1))
      mpk %= MAX
    if 0 < k <= n:
      mkpnk *= pow(m - (k - 1), MAX-2, MAX) 
      mkpnk %= MAX
    s += nck * ( (-1) ** k) * mpk * (mkpnk) ** 2
    s %= MAX
  print(s)
  

if __name__=='__main__':
  main()
Problem p02762 (python)

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

from collections import defaultdict
import sys
sys.setrecursionlimit(10**5+10)

def main():
  n, m, k = map(int, input().strip().split())
  friends = defaultdict(lambda :{'children':list(), 'x':-1, 'visited':False})
  blocks = defaultdict(list)
  visited = set()
  
  for _ in range(m):
    a, b = map(int, input().strip().split())
    friends[a]['children'].append(b)
    friends[b]['children'].append(a)

  for _ in range(k):
    c, d = map(int, input().strip().split())
    blocks[c].append((d))
    blocks[d].append((c))
    
  def dfs(i, x):
    friends[i]['x'] = x
    friends[i]['visited'] = True
    count = 1
    for child in friends[i]['children']:
      if friends[child]['visited']:
        continue
      count += dfs(child, x)
    return count
  
  num = 1
  size = dict()
  for i in range(1, n+1):
    if friends[i]['visited']:
      continue
    count = dfs(i, num)
    size[num] = count
    num += 1
    
  ans = []
  for i in range(1, n+1):
    nblock = 0
    for ib in blocks[i]:
      if friends[i]['x'] == friends[ib]['x']:
        nblock += 1
    ans.append(size[friends[i]['x']] - len(friends[i]['children']) - nblock - 1)
  print(' '.join(list(map(str, ans))))
  
if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/python3
# -*- coding:utf-8 -*-

from collections import defaultdict

def main():
  n, m, k = map(int, input().strip().split())
  friends = defaultdict(lambda :{'children':list(), 'x':-1, 'visited':False})
  blocks = defaultdict(list)
  visited = set()
  
  for _ in range(m):
    a, b = map(int, input().strip().split())
    friends[a]['children'].append(b)
    friends[b]['children'].append(a)

  for _ in range(k):
    c, d = map(int, input().strip().split())
    blocks[c].append((d))
    blocks[d].append((c))
    
  def dfs(i, x):
    friends[i]['x'] = x
    friends[i]['visited'] = True
    count = 1
    for child in friends[i]['children']:
      if friends[child]['visited']:
        continue
      count += dfs(child, x)
    return count
  
  num = 1
  size = dict()
  for i in range(1, n+1):
    if friends[i]['visited']:
      continue
    count = dfs(i, num)
    size[num] = count
    num += 1
    
  ans = []
  for i in range(1, n+1):
    nblock = 0
    for ib in blocks[i]:
      if friends[i]['x'] == friends[ib]['x']:
        nblock += 1
    ans.append(size[friends[i]['x']] - len(friends[i]['children']) - nblock - 1)
  print(' '.join(list(map(str, ans))))
  
if __name__=='__main__':
  main()
Problem p02793 (python)

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

def calc_gcd(a, b):
  if a > b:
    a, b = b, a
  while True:
    a, b = b%a, a
    if a == 0:
      return b

def calc_lcm(a, b):
  gcd = calc_gcd(a, b)
  return int(a * b // gcd)

def main():
  n = int(input())
  As = list(map(int, input().strip().split()))
  lcm = As[0]
  total = 0
  for a in As[1:]:
    lcm = calc_lcm(lcm, a)
  for a in As:
    total += lcm // a
  print(total % (10**9+7))


if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/python3
# -*- coding:utf-8 -*-

def calc_gcd(a, b):
  if a > b:
    a, b = b, a
  while True:
    a, b = b%a, a
    if a == 0:
      return b

def calc_lcm(a, b):
  gcd = calc_gcd(a, b)
  return int(a * b / gcd)

def main():
  n = int(input())
  As = list(map(int, input().strip().split()))
  lcm = As[0]
  total = 0
  for a in As[1:]:
    lcm = calc_lcm(lcm, a)
  for a in As:
    total += lcm / a
  print(int(total) % (10**9+7))


if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/python3
# -*- coding:utf-8 -*-

def calc_gcd(a, b):
  if a > b:
    a, b = b, a
  a, b = b%a, a
  if a != 0:
    return calc_gcd(a, b)
  else:
    return b

def calc_lcm(a, b):
  gcd = calc_gcd(a, b)
  return int(a * b / gcd)

def main():
  n = int(input())
  As = list(map(int, input().strip().split()))
  lcm = As[0]
  total = 0
  for a in As[1:]:
    lcm = calc_lcm(lcm, a)
  for a in As:
    total += lcm / a
  print(int(total) % (10**9+7))


if __name__=='__main__':
  main()
Problem p02948 (python)

Fixed submission:
# -*- coding:utf-8 -*-
# /usr/bin/python3

from heapq import heappush, heappop

def main():
  n, m = map(int, input().strip().split(' '))
  liAB = [tuple(map(int, input().strip().split(' '))) for _ in range(n)]
  liAB.sort(key=lambda x:x[0])

  k = 1
  top = []
  s = 0
  for a, b in liAB:
    if a >= m+1:
      break

    if k < a:
      s += (-sum([heappop(top) for _ in range(a-k) if len(top) != 0]))
      k = a
    heappush(top, -b)

  s += (-sum([heappop(top) for _ in range(m-k+1) if len(top) != 0]))
  print(s)

if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
# -*- coding:utf-8 -*-
# /usr/bin/python3

from bisect import insort
from collections import deque

def main():
  n, m = map(int, input().strip().split(' '))
  liAB = sorted([tuple(map(int, input().strip().split(' '))) for _ in range(n)], key=lambda x:x[0])

  k = 1
  top = deque()
  s = 0
  for a, b in liAB:
    if a >= m+1:
      break

    if k < a:
      for i in range(len(top)):
        if i < a-k:
          s += top[-1]
          del top[-1]
      k = a

    insort(top, b)


  s += top[-1]
  for i in range(m - k):
    s += top[-(i+1)]

  print(s)
  
  pass

if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
# -*- coding:utf-8 -*-
# /usr/bin/python3

from collections import defaultdict
from bisect import insort
from collections import deque

def main():
  n, m = map(int, input().strip().split(' '))
  liAB = sorted([tuple(map(int, input().strip().split(' '))) for _ in range(n)], 
                key=lambda x:x[0])

  k = 1
  top = deque()
  s = 0
  for a, b in liAB:
    if a >= m+1:
      break

    if k < a:
      for i in range(len(top)):
        if i < a-k:
          s += top[-1]
          del top[-1]
      k = a

    insort(top, b)


  s += top[-1]
  for i in range(m - k):
    s += top[-(i+1)]

  print(s)
  
  pass

if __name__=='__main__':
  main()
Problem p03053 (python)

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

from queue import deque

def main():
  h, w = map(int, input().split())
  grids = [False] * (w * h)
  dq = deque()
  for i in range(h):
    for j, c in enumerate(list(input().strip())):
      if c == '#':
        grids[i*w + j] = True
        dq.append((0, i, j))
  
  while dq:
    cnt, i, j = dq.popleft()
    for dx, dy in zip([-1, 0, 1, 0], [0, -1, 0, 1]):
      if 0 <= i+dx < h and 0 <= j+dy < w and not grids[(i+dx)*w + (j+dy)]:
        grids[(i+dx)*w + (j+dy)] = True
        dq.append((cnt+1, i+dx, j+dy))
  print(cnt)
  
if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/python3
# -*- coding:utf-8 -*-

from queue import deque

def main():
  h, w = map(int, input().split())
  grids = [False] * (w * h)
  dq = deque()
  for j in range(h):
    for i, c in enumerate(list(input().strip())):
      if c == '#':
        grids[w*i + j] = True
        dq.append((0, i, j))
  
  while dq:
    cnt, i, j = dq.popleft()
    for dx, dy in zip([-1, 0, 1, 0], [0, -1, 0, 1]):
      if 0 <= i+dx < w and 0 <= j+dy < h and not grids[(i+dx)*w + (j+dy)]:
        grids[(i+dx)*w + (j+dy)] = True
        dq.append((cnt+1, i+dx, j+dy))
  print(cnt)
  
if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/python3
# -*- coding:utf-8 -*-

from queue import deque

def main():
  h, w = map(int, input().split())
  grids = [list(input().strip()) for _ in range(h)]
  dq = deque()
  for i in range(w):
    for j in range(h):
      if grids[i][j] == '#':
        dq.append((0, i, j))
  
  mcnt = -1
  while dq:
    cnt, i, j = dq.popleft()
    mcnt = cnt if cnt > mcnt else mcnt
    for dx, dy in zip([-1, 0, 1, 0], [0, -1, 0, 1]):
      if 0 <= i+dx < h and 0 <= j+dy < w and grids[i+dx][j+dy] == '.':
        grids[i+dx][j+dy] = '#'
        dq.append((cnt+1, i+dx, j+dy))
  print(cnt)
  
if __name__=='__main__':
  main()
Problem p03326 (python)

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

def main():
  n, m = map(int, input().split())
  lxyz = [[0]*3 for _ in range(n)]
  for i in range(n):
    lxyz[i] = list(map(int, input().split()))
  
  def binary(x, k, t=1, f=0):
    return [t if (x >> ik)%2 else f for ik in range(k)]
  
  ans = -1
  for lh in [binary(i, 3, f=-1) for i in range(8)]:
    ans = max(ans, abs(sum(sorted([sum(map(lambda x: x[0]*x[1], zip(lh, lxyz[i]))) for i in range(n)], reverse=True)[:m]))) 
  print(ans)
  
if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/python3
# -*- coding:utf-8 -*-


def main():
  n, m = map(int, input().split())
  lxyz = [[0]*3 for _ in range(n)]
  for i in range(n):
    lxyz[i] = list(map(int, input().split()))
  
  def binary(x, k, t=1, f=0):
    return [t if (x >> ik)%2 else f for ik in range(k)]
  
  def calc_dp(lxyz):
    dp = [[0] * m for _ in range(n)]

    max_score = -(10 ** 15) 
    for i in range(n):
      max_score = max(lxyz[i], max_score)
      dp[i][0] = max_score
      
    for i in range(1, n):
      for j in range(1, m):
        if i == j == 0: 
          continue
        dp[i][j] = max(dp[i-1][j-1] + lxyz[i], dp[i-1][j])
    return dp[-1][-1]
    
  ans = -1
  for lh in [binary(i, 3, f=-1) for i in range(8)]:
    ans = max(ans, abs(calc_dp([sum(map(lambda x: x[0]*x[1], zip(lh, lxyz[i]))) for i in range(n)]))) 
  print(ans)
  
if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/python3
# -*- coding:utf-8 -*-


def main():
  n, m = map(int, input().split())
  lxyz = [[0]*3 for _ in range(n)]
  for i in range(n):
    lxyz[i] = list(map(int, input().split()))
  
  def binary(x, k, t=1, f=0):
    return [t if (x >> ik)%2 else f for ik in range(k)]
  
  def calc_dp(lxyz):
    dp = [
      [
        [0] * 3
        for _ in range(m)]
      for _ in range(n)]

    max_score = -(10 ** 15) 
    max_xyz = lxyz[0]
    for i in range(n):
      score = sum(lxyz[i])
      if score > max_score:
        max_xyz = lxyz[i]
        max_score = score
      dp[i][0] = max_xyz
      
    for i in range(1, n):
      for j in range(1, m):
        if i == j == 0: 
          continue
        use_i = list(map(sum, zip(dp[i-1][j-1], lxyz[i])))
        if sum(use_i) > sum(dp[i-1][j]):
          dp[i][j] = use_i
        else:
          dp[i][j] = dp[i-1][j]
    return sum(dp[-1][-1])
    
  
  ans = -1
  for lh in [binary(i, 3, f=-1) for i in range(8)]:
    _lxyz = [[0]*3 for _ in range(n)]
    for j, h in enumerate(lh):
        for i in range(n):
          _lxyz[i][j] = h * lxyz[i][j]    
    ans = max(ans, abs(calc_dp(_lxyz))) 
  print(ans)
  
if __name__=='__main__':
  main()
Problem p03426 (python)

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

import numpy
from collections import defaultdict

def main():
  h, w, d = map(int, input().split())
  mat_a = numpy.array([list(map(int, input().split())) for _ in range(h)])
  q = int(input())
  x_to_pos = dict()
  
  for i in range(h):
    for j in range(w):
      x_to_pos[mat_a[i, j]] = (i, j)
      
  def calc_score(p1, p2):
    return sum([abs(x-y) for x, y in zip(p1, p2)])
  
  visited = numpy.zeros((h, w))
  costs = defaultdict(dict)
  for c in range(1, d+1):
    cost = 0
    costs[c%d][c] = 0
    while True:
      cp = x_to_pos[c]
      c += d
      if c > (h*w):
        break
      np = x_to_pos[c]
      cost += calc_score(cp, np)
      costs[c%d][c] = cost
  
  for _ in range(q):
    l, r = map(int, input().split())
    print(abs(costs[l%d][l] - costs[l%d][r]))

if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/python3
# -*- coding:utf-8 -*-

import numpy
from collections import defaultdict

def main():
  h, w, d = map(int, input().split())
  mat_a = numpy.array([list(map(int, input().split())) for _ in range(h)])
  q = int(input())
  x_to_pos = dict()
  
  for i in range(h):
    for j in range(w):
      x_to_pos[mat_a[i, j]] = (i, j)
      
  def calc_score(p1, p2):
    return sum([abs(x-y) for x, y in zip(p1, p2)])
  
  visited = numpy.zeros((h, w))
  costs = defaultdict(dict)
  for x in range(1, d+1):
    c = x
    cost = 0
    costs[c%d][c%d] = 0
    while True:
      cp = x_to_pos[c]
      c += d
      if c > (h*w):
        break
      np = x_to_pos[c]
      cost += calc_score(cp, np)
      costs[c%d][c] = cost
      
  for _ in range(q):
    cost = 0
    l, r = map(int, input().split())
    print(abs(costs[l%d][l] - costs[l%d][r]))

if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/python3
# -*- coding:utf-8 -*-

import numpy
from collections import defaultdict

def main():
  h, w, d = map(int, input().split())
  mat_a = numpy.array([list(map(int, input().split())) for _ in range(h)])
  q = int(input())
  x_to_pos = dict()
  
  for i in range(h):
    for j in range(w):
      x_to_pos[mat_a[i, j]] = (i, j)
      
  def calc_score(p1, p2):
    return sum([abs(x-y) for x, y in zip(p1, p2)])
  
  visited = numpy.zeros((h, w))
  costs = defaultdict(dict)
  for x in numpy.sort(mat_a.reshape(-1)):
    c = x
    cost = 0
    costs[c%d][c%d] = 0
    if x > d:
      continue
    while True:
      cp = x_to_pos[c]
      c += d
      if c not in x_to_pos.keys():
        break
      np = x_to_pos[c]
      cost += calc_score(cp, np)
      costs[c%d][c] = cost
      
  for _ in range(q):
    cost = 0
    l, r = map(int, input().split())
    if l == r:
      print(0)
    else:
#       print(l, r, l%d, costs)
      print(abs(costs[l%d][l] - costs[l%d][r]))

if __name__=='__main__':
  main()
Problem p03634 (python)

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

import sys
sys.setrecursionlimit(10**9)

def main():
  n = int(input())
  inode2scores = [0] * (n+1)
  tree = [[] for _ in range(n+1)]
  weights = dict()
  for _ in range(n-1):
    a, b, c = map(int, input().split())
    tree[a].append(b)
    tree[b].append(a)
    weights[(a, b)] = weights[(b, a)] = c
    
  q, k = map(int, input().split())  
  visited = [False] * (n+1)
  iroot = k
  def dfs(inode, score=0):
    visited[inode] = True
    for ichild in tree[inode]:
      if visited[ichild]:
        continue
      inode2scores[ichild] = weights[(inode, ichild)] + score
      dfs(ichild, inode2scores[ichild])
  dfs(iroot)
  for _ in range(q):
    x, y = map(int, input().split())
    print(inode2scores[x] + inode2scores[y])

if __name__=='__main__':
  main()

Buggy submission (verdict: Runtime Error):
#!/usr/bin/python3
# -*- coding:utf-8 -*-

from collections import defaultdict

def main():
  n = int(input())
  tree = defaultdict(lambda : {'parent':-1, 'score':0, 'children':[]})
  weights = dict()
  for _ in range(n-1):
    a, b, c = map(int, input().split())
    tree[a]['children'].append(b)
    tree[b]['children'].append(a)
    weights[(a, b)] = weights[(b, a)] = c
    
  q, k = map(int, input().split())  
  visited = []
  iroot = k
  def dfs(inode, score=0):
    visited.append(inode)
    for ichild in tree[inode]['children']:
      if ichild in visited:
        continue
      tree[ichild]['score'] = weights[(inode, ichild)] + score
      tree[ichild]['parent'] = inode
      dfs(ichild, tree[ichild]['score'])
  dfs(iroot)
  for _ in range(q):
    x, y = map(int, input().split())
    print(tree[x]['score'] + tree[y]['score'])

if __name__=='__main__':
  main()