Harryxun/testdata huggingface dataset:
Buggy python submission (verdict: Runtime Error):
import sys
input = sys.stdin.readline
from collections import deque

MOD = 10 ** 9 + 7

N = int(input())
graph = [[] for _ in range(N+1)]
for i,x in enumerate(input().rstrip().split(),1):
    x = int(x)
    graph[i].append(x)
    graph[x].append(i)

# 各深さから来ている (0個、1個、2個以上) の分布を 確率 mod MODで持つ。

half = (MOD + 1) // 2

def merge(dp,dp1):
    L = len(dp1)
    for i in range(L):
        # 0個,1個,2個以上
        a,b,c = dp[i]
        d,e,f = dp1[i]
        a,b,c = a*d, a*e + b*d, a*f + b*e + b*f + c*d + c*e + c*f
        a %= MOD
        b %= MOD
        c %= MOD
        dp[i] = (a,b,c)
    return

def dfs(v,parent = None):
    dp = None
    L = 0
    for u in graph[v]:
        if u == parent:
            continue
        dp1 = dfs(u,v)
        if dp is None:
            dp = dp1
        else:
            if len(dp) < len(dp1):
                dp,dp1 = dp1,dp
            # 2個以上が入っているインデックス
            if L < len(dp1):
                L = len(dp1)
            merge(dp,dp1)
    if dp is None:
        dp = deque()
    else:
        # 2個以上あるときに、0個化する
        for i in range(L):
            a,b,c = dp[i]
            dp[i] = (a+c,b,0)
    dp.appendleft((half,half,0))
    return dp

dp = dfs(0)

answer = sum(b for a,b,c in dp)
answer *= pow(2,N+1,MOD)
answer %= MOD
print(answer)

Fixed submission:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import deque

MOD = 10 ** 9 + 7

N = int(input())
graph = [[] for _ in range(N+1)]
for i,x in enumerate(input().rstrip().split(),1):
    x = int(x)
    graph[i].append(x)
    graph[x].append(i)

# 各深さから来ている (0個、1個、2個以上) の分布を 確率 mod MODで持つ。

half = (MOD + 1) // 2

def merge(dp,dp1):
    L = len(dp1)
    for i in range(L):
        # 0個,1個,2個以上
        a,b,c = dp[i]
        d,e,f = dp1[i]
        a,b,c = a*d, a*e + b*d, a*f + b*e + b*f + c*d + c*e + c*f
        a %= MOD
        b %= MOD
        c %= MOD
        dp[i] = (a,b,c)
    return

def dfs(v,parent = None):
    dp = None
    L = 0
    for u in graph[v]:
        if u == parent:
            continue
        dp1 = dfs(u,v)
        if dp is None:
            dp = dp1
        else:
            if len(dp) < len(dp1):
                dp,dp1 = dp1,dp
            # 2個以上が入っているインデックス
            if L < len(dp1):
                L = len(dp1)
            merge(dp,dp1)
    if dp is None:
        dp = deque()
    else:
        # 2個以上あるときに、0個化する
        for i in range(L):
            a,b,c = dp[i]
            dp[i] = (a+c,b,0)
    dp.appendleft((half,half,0))
    return dp

dp = dfs(0)

answer = sum(b for a,b,c in dp)
answer *= pow(2,N+1,MOD)
answer %= MOD
print(answer)
Buggy python submission (verdict: Runtime Error):
N = int(input())

def F(x):
  if x < 10:
    return x
  return x%10 + F(x//10)

answer = 'YES' if x%F(N) == 0 else 'NO'
print(answer)

Fixed submission:
N = int(input())

def F(x):
  if x < 10:
    return x
  return x%10 + F(x//10)

answer = 'Yes' if N%F(N) == 0 else 'No'
print(answer)

Buggy python submission (verdict: Runtime Error):
N = int(input())

def F(x):
  if x < 10:
    return x
  return x%10 + F(x//10)

answer = 'YES' if x%F(x) == 0 else 'NO'
print(answer)

Fixed submission:
N = int(input())

def F(x):
  if x < 10:
    return x
  return x%10 + F(x//10)

answer = 'Yes' if N%F(N) == 0 else 'No'
print(answer)
Buggy python submission (verdict: Time Limit Exceeded):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

N,Q = map(int,input().split())
VW = [[int(x) for x in input().split()] for _ in range(Q)]

if N == 1:
    answer = [str(min(v,w)) for v,w in VW]
else:
    answer = []
    for v,w in VW:
        while v != w:
            if v > w:
                v,w = w,v
            w = (w+N-2)//N
        answer.append(str(v))

print('\n'.join(answer))

Fixed submission:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

import numpy as np

N,Q = map(int,input().split())
V,W = np.array([input().split() for _ in range(Q)],dtype=np.int64).T

if N == 1:
    answer = np.minimum(V,W)
else:
    for _ in range(50):
        V[V>W] = (V[V>W]+N-2)//N
        W[W>V] = (W[W>V]+N-2)//N
    answer = V

print('\n'.join(answer.astype(str)))

Buggy python submission (verdict: Time Limit Exceeded):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

N,Q = map(int,input().split())
VW = [[int(x) for x in input().split()] for _ in range(Q)]

if N == 1:
    answer = [min(v,w) for v,w in VW]
else:
    answer = []
    for v,w in VW:
        while v != w:
            if v > w:
                v,w = w,v
            w = (w+N-2)//N
        answer.append(v)

print('\n'.join(map(str,answer)))

Fixed submission:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

import numpy as np

N,Q = map(int,input().split())
V,W = np.array([input().split() for _ in range(Q)],dtype=np.int64).T

if N == 1:
    answer = np.minimum(V,W)
else:
    for _ in range(50):
        V[V>W] = (V[V>W]+N-2)//N
        W[W>V] = (W[W>V]+N-2)//N
    answer = V

print('\n'.join(answer.astype(str)))
Buggy python submission (verdict: Time Limit Exceeded):
from collections import deque

# 1から初めて、xがあるとき10x、x+1のいずれかが行えるとしてqueue

K = int(input())
q = deque()
q.append((1,1)) # 各桁の和、modulo K
visited = [False]*K

ans = 0

while ans == 0:
  s,x = q.popleft()
  visited[x] = True
  if x == 0:
    ans = s
    break
  q.appendleft((s,(10*x)%K))
  q.append((s+1,(x+1)%K))

print(ans)

Fixed submission:
from collections import deque
 
# 1から初めて、xがあるとき10x、x+1のいずれかが行えるとしてqueue
 
K = int(input())
q = deque()
q.append((1,1)) # 各桁の和、modulo K
visited = [False]*K
 
ans = 0
 
while ans == 0:
  s,x = q.popleft()
  if visited[x]:
    continue
  visited[x] = True
  if x == 0:
    ans = s
    break
  q.appendleft((s,(10*x)%K))
  q.append((s+1,(x+1)%K))
 
print(ans)

Buggy python submission (verdict: Time Limit Exceeded):
import heapq
 
# 1から初めて、xがあるとき10x、x+1のいずれかが行えるとしてqueue
 
K = int(input())
h = []
heapq.heappush(h,(1,1)) # 各桁の和、modulo K
visited = [False]*K
 
ans = 0
 
while ans == 0:
  s,x = heapq.heappop(h)
  visited[x] = True
  for ss,xx in [(s,(10*x)%K), (s+1,(x+1)%K)]:
    if visited[xx]:
      continue
    if xx == 0:
      ans = ss
      break
    heapq.heappush(h,(ss,xx))
  
print(ans)

Fixed submission:
from collections import deque
 
# 1から初めて、xがあるとき10x、x+1のいずれかが行えるとしてqueue
 
K = int(input())
q = deque()
q.append((1,1)) # 各桁の和、modulo K
visited = [False]*K
 
ans = 0
 
while ans == 0:
  s,x = q.popleft()
  if visited[x]:
    continue
  visited[x] = True
  if x == 0:
    ans = s
    break
  q.appendleft((s,(10*x)%K))
  q.append((s+1,(x+1)%K))
 
print(ans)

Buggy python submission (verdict: Time Limit Exceeded):
import numpy as np
import heapq

# 1から初めて、xがあるとき10x、x+1のいずれかが行えるとしてqueue

K = int(input())
h = []
heapq.heappush(h,(1,1)) # 各桁の和、modulo K
visited = np.full(K,False)

ans = 0

while ans == 0:
  s,x = heapq.heappop(h)
  visited[x] = True
  for ss,xx in [(s,(10*x)%K), (s+1,(x+1)%K)]:
    if visited[xx]:
      continue
    if xx == 0:
      ans = ss
      break
    heapq.heappush(h,(ss,xx))
  
print(ans)

Fixed submission:
from collections import deque
 
# 1から初めて、xがあるとき10x、x+1のいずれかが行えるとしてqueue
 
K = int(input())
q = deque()
q.append((1,1)) # 各桁の和、modulo K
visited = [False]*K
 
ans = 0
 
while ans == 0:
  s,x = q.popleft()
  if visited[x]:
    continue
  visited[x] = True
  if x == 0:
    ans = s
    break
  q.appendleft((s,(10*x)%K))
  q.append((s+1,(x+1)%K))
 
print(ans)
Buggy python submission (verdict: Runtime Error):
r=input()
g=input()
print(2*g-r)

Fixed submission:
r=int(input())
g=int(input())
print(2*g-r)
Buggy python submission (verdict: Runtime Error):
# 各時点で最小

N,K = map(int,input().split())

answer = 1
for _ in range(N):
  answer = min(answer*2, answer+K)

print(answer)

Fixed submission:
# 各時点で最小

N,K = int(input()), int(input())

answer = 1
for _ in range(N):
  answer = min(answer*2, answer+K)

print(answer)
Buggy python submission (verdict: Time Limit Exceeded):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

import numpy as np

S = np.array(list(read().rstrip()),np.int32)

Scum = np.bitwise_xor.accumulate(1<<(S-97)).tolist()

bit = 1<<np.arange(26)

INF = 10**9
dp = np.full(1<<26,INF,np.int32)
dp[0] = 0

for cum in Scum:
    x = dp[cum^bit].min() + 1
    if dp[cum] > x:
        dp[cum] = x

answer = max(1,dp[cum])
print(answer)

Fixed submission:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

S = read().rstrip()

from collections import defaultdict

INF = 10**9
dp = defaultdict(lambda:INF)
dp[0] = 0

cum = 0
for x in S:
    cum ^= 1<<(x-97)
    x = min(dp[cum^(1<<i)] for i in range(26)) + 1
    if dp[cum] > x:
        dp[cum] = x

answer = max(1,dp[cum])
print(answer)

Buggy python submission (verdict: Time Limit Exceeded):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

S = read().rstrip()

from collections import defaultdict

INF = 10**9
dp = defaultdict(lambda:INF)
dp[0] = 0

cum = 0
for x in S:
    cum ^= 1<<(x-97)
    x = min(dp[cum^(1<<i)] for i in range(26)) + 1
    if dp[cum] > x:
        dp[cum] = x

answer = max(1,dp[cum])
print(answer)

Fixed submission:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

S = read().rstrip()

from collections import defaultdict

INF = 10**9
dp = defaultdict(lambda:INF)
dp[0] = 0

cum = 0
for x in S:
    cum ^= 1<<(x-97)
    x = min(dp[cum^(1<<i)] for i in range(26)) + 1
    if dp[cum] > x:
        dp[cum] = x

answer = max(1,dp[cum])
print(answer)
Buggy python submission (verdict: Runtime Error):
from collections import Counter
N = int(input())
D = [int(x) for x in input().split()]
M = int(input())
T = [int(x) for x in input().split()]

c = Counter(D) - Counter(T)
answer = 'YES' if min(c.values()) >= 0 else 'NO'
print(answer)

Fixed submission:
from collections import defaultdict
N = int(input())
D = [int(x) for x in input().split()]
M = int(input())
T = [int(x) for x in input().split()]

cnt = defaultdict(int)
for d in D:
  cnt[d] += 1
for t in T:
  cnt[t] -= 1

answer = 'YES' if min(cnt.values()) >= 0 else 'NO'
print(answer)
Buggy python submission (verdict: Time Limit Exceeded):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
ABC = list(map(int,read().split()))
A = ABC[::3]; B = ABC[1::3]; C = ABC[2::3]

class BIT():
    def __init__(self, max_n):
        self.size = max_n + 1
        self.tree = [0] * self.size
        
    def get_sum(self,i):
        s = 0
        while i:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i < self.size:
            self.tree[i] += x
            i += i & -i

def Inversion(seq):
    # seqは、1,2,...,Nの順列
    N = len(seq)
    bit = BIT(N)
    inv = N*(N-1)//2
    for x in seq:
        inv -= bit.get_sum(x)
        bit.add(x,1)
    return inv

def get_rank(seq):
    x_to_i = {x:i for i,x in enumerate(sorted(seq))}
    return [1+x_to_i[x] for x in seq]

def solve_x(A,B,C):
    M = (N*(N-1)//2+1)//2 # 必要な交点個数
    U = 2*10**8 + 100 # 交点の座標の上界
    left = -U # 交点の個数の合計が M 個に満たない
    right = U # 交点の個数の合計が M 個以上である
    # x = -inf における y の順序
    order = sorted(range(N),key = lambda i: A[i]/B[i])
    def test(x):
        y = [(C[i]-A[i]*x)/(B[i]) for i in order]
        seq = get_rank(y)
        return Inversion(seq) >= M
    
    for _ in range(60):
        mid = (left + right)/2
        if test(mid):
            right = mid
        else:
            left = mid
    return (left + right)/2

x = solve_x(A,B,C)
y = solve_x(B,A,C)
print(x,y)



Fixed submission:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
ABC = list(map(int,read().split()))
A = ABC[::3]; B = ABC[1::3]; C = ABC[2::3]

class BIT():
    def __init__(self, max_n):
        self.size = max_n + 1
        self.tree = [0] * self.size
        
    def get_sum(self,i):
        s = 0
        while i:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i < self.size:
            self.tree[i] += x
            i += i & -i

def Inversion(seq):
    # seqは、1,2,...,Nの順列
    N = len(seq)
    bit = BIT(N)
    inv = N*(N-1)//2
    for x in seq:
        inv -= bit.get_sum(x)
        bit.add(x,1)
    return inv

def get_rank(seq):
    x_to_i = {x:i for i,x in enumerate(sorted(seq))}
    return [1+x_to_i[x] for x in seq]

def solve_x(A,B,C):
    M = (N*(N-1)//2+1)//2 # 必要な交点個数
    U = 2*10**8 + 100 # 交点の座標の上界
    left = -U # 交点の個数の合計が M 個に満たない
    right = U # 交点の個数の合計が M 個以上である
    # x = -inf における y の順序
    order = sorted(range(N),key = lambda i: A[i]/B[i])
    def test(x):
        y = [(C[i]-A[i]*x)/(B[i]) for i in order]
        seq = get_rank(y)
        return Inversion(seq) >= M
    
    for _ in range(60):
        mid = (left + right)/2
        if test(mid):
            right = mid
        else:
            left = mid
    return (left + right)/2

x = solve_x(A,B,C)
y = solve_x(B,A,C)
print(x,y)
Buggy python submission (verdict: Runtime Error):
n,a = map(int,input().split())
print(n*n-a)

Fixed submission:
print(int(input())**2-int(input()))
Buggy python submission (verdict: Runtime Error):
import itertools

A,B,C,D,E,F = map(int,input().split())

WF = F//100+1

water = [False] * (WF+1+30)
sugar = [False] * (F+1+30)

water[0] = True
sugar[0] = True

for n in range(WF):
  if water[n]:
    water[n+A] = True
    water[n+B] = True
for n in range(F):
  if sugar[n]:
    sugar[n+C] = True
    sugar[n+D] = True

water = set(100*x for x in range(1,1+WF) if water[x])
sugar = set(x for x in range(1,1+F) if sugar[x])

# at most 30 * 3000なので全てやる
ans_per = -1
for w, s in itertools.product(water, sugar):
  if w//100*E < s:
    continue
  if w+s > F:
    continue
  x = s/(w+s)
  if x > ans_per:
    ans_per = x
    ans_w = w
    ans_s = s

print(ans_w + ans_s, ans_s)

Fixed submission:
import itertools

A,B,C,D,E,F = map(int,input().split())

WF = F//100+1

water = [False] * (WF+1+30)
sugar = [False] * (F+1+30)

water[0] = True
sugar[0] = True

for n in range(WF):
  if water[n]:
    water[n+A] = True
    water[n+B] = True
for n in range(F):
  if sugar[n]:
    sugar[n+C] = True
    sugar[n+D] = True

water = set(100*x for x in range(1,1+WF) if water[x])
sugar = set(x for x in range(1+F) if sugar[x])

# at most 30 * 3000なので全てやる
ans_per = -1
for w, s in itertools.product(water, sugar):
  if w//100*E < s:
    continue
  if w+s > F:
    continue
  x = s/(w+s)
  if x > ans_per:
    ans_per = x
    ans_w = w
    ans_s = s

print(ans_w + ans_s, ans_s)
Buggy python submission (verdict: Runtime Error):
import numpy as np
N = int(input())
A = np.array(input().split(), dtype = np.int32)

counter = np.bincount(A)
answer = (counter[2:] + counter[1:-1] + counter[:-2]).max()
print(answer)

Fixed submission:
import numpy as np
# 前後1まで回収できる
N = int(input())

# n以下のものをかぞえる
A = np.bincount(np.array(input().split(), dtype=np.int32))

B = A.copy() # そのままとる
B[1:] += A[:-1] # 1増やして回収
B[:-1] += A[1:] # 1減らして回収

answer = B.max()
print(answer)
Buggy python submission (verdict: Runtime Error):
N = int(input())

def gcd(a,b):
  while b:
    a,b = b,a%b
  return a

answer = 0
for _ in range(N):
  answer = gcd(answer, int(input())
               
print(answer)

Fixed submission:
N = int(input())

def gcd(a,b):
  while b:
    a,b = b,a%b
  return a

answer = 1
for _ in range(N):
  x = int(input())
  answer *= x//gcd(answer, x)
               
print(answer)
Buggy python submission (verdict: Runtime Error):
n,k = map(int,input().split())
A = [int(x) for x in input().split()]
A.sort()

answer = sum(A[-K:])
print(answer)

Fixed submission:
n,k = map(int,input().split())
A = [int(x) for x in input().split()]
A.sort()

answer = sum(A[-k:])
print(answer)
Buggy python submission (verdict: Runtime Error):
# 木グラフなので各プレイヤから近い点の個数を比べればよい

N = int(input())

edge = [[] for _ in range(N)]

for _ in range(N-1):
  a,b = map(int,input().split())
  edge[a-1].append(b-1)  
  edge[b-1].append(a-1)  

INF = 10**18

d_fe = [INF]*N
d_sn = [INF]*N

d_fe[0] = 0
d_sn[-1] = 0

def f(d,x):
  dx = d[x]
  for v in edge[x]:
    if d[v] == INF:
      d[v] = dx+1
      f(d,v)
      
f(d_fe,0)
f(d_sn,N-1)

black = 0
white = 0

for x in range(N):
  if d_fe[x] <= d_sn[x]:
    black += 1
  else:
    white += 1

answer = 'Fennec' if black > white else 'Snuke'
print(answer)

Fixed submission:
import sys
sys.setrecursionlimit(10**6)
# 木グラフなので各プレイヤから近い点の個数を比べればよい

N = int(input())

edge = [[] for _ in range(N)]

for _ in range(N-1):
  a,b = map(int,input().split())
  edge[a-1].append(b-1)  
  edge[b-1].append(a-1)  

INF = 10**18

d_fe = [INF]*N
d_sn = [INF]*N

d_fe[0] = 0
d_sn[N-1] = 0

def f(d,x):
  dx = d[x]
  for v in edge[x]:
    if d[v] == INF:
      d[v] = dx+1
      f(d,v)
      
f(d_fe,0)
f(d_sn,N-1)

black = 0
white = 0

for x in range(N):
  if d_fe[x] <= d_sn[x]:
    black += 1
  else:
    white += 1

answer = 'Fennec' if black > white else 'Snuke'
print(answer)
Buggy python submission (verdict: Runtime Error):
N,P = int(input())
A = [int(x) for x in input().split()]

odd = sum(x&1 for x in A)

if odd:
  # どちらも半分ずつ
  answer = 2**(N-1)
else:
  answer = (2 ** N) * P

print(answer)

Fixed submission:
N,P = map(int,input().split())
A = [int(x) for x in input().split()]

odd = sum(x&1 for x in A)

if odd:
  # どちらも半分ずつ
  answer = 2**(N-1)
else:
  answer = (2 ** N) * (1-P)

print(answer)
Buggy python submission (verdict: Runtime Error):
import numpy as np
import numba as nb

# 基本的に重複がない
# n+1Ck − (n+1)-(r-l+1)Ck−1

MOD = 10**9+7
U = 10**5 + 1

def power_mod(a,n):
  if n == 0:
    return 1
  x = (power_mod(a,n//2)**2)%MOD
  return x if n%2 == 0 else (a*x)%MOD

@nb.njit
def make_fact(fact,fact_inv):
  for i in range(1,U+1):
    fact[i] = (fact[i-1]*i)%MOD
  fact_inv[U] = power_mod(fact[U],MOD-2)
  for i in range(U,0,-1):
    fact_inv[i-1] = (fact_inv[i]*i)%MOD

def comb(n,k):
  if k < 0 or k > n:
    return 0
  x = fact[n]
  x *= fact_inv[k]
  x %= MOD
  x *= fact_inv[n-k]
  x %= MOD
  return x

fact = np.ones(U+1,dtype = np.int64)
fact_inv = np.ones(U+1,dtype = np.int64)
make_fact(fact,fact_inv)

# 重複の起きる場所の間隔だけが問題
n = int(input())
A = [int(x) for x in input().split()]

memo = dict()
d = 0
for i,x in enumerate(A):
  if x in memo:
    d = i - memo[x]
    break
  memo[x] = i

rest = n-d

for k in range(1,n+2):
  ans = comb(n+1,k) - comb(rest,k-1)
  ans %= MOD
  print(ans)


Fixed submission:
# 基本的に重複がない
# n+1Ck − (n+1)-(r-l+1)Ck−1

MOD = 10**9+7
U = 10**5 + 1

def power_mod(a,n):
  if n == 0:
    return 1
  x = (power_mod(a,n//2)**2)%MOD
  return x if n%2 == 0 else (a*x)%MOD

def make_fact(fact,fact_inv):
  for i in range(1,U+1):
    fact[i] = (fact[i-1]*i)%MOD
  fact_inv[U] = power_mod(fact[U],MOD-2)
  for i in range(U,0,-1):
    fact_inv[i-1] = (fact_inv[i]*i)%MOD

def comb(n,k):
  if k < 0 or k > n:
    return 0
  x = fact[n]
  x *= fact_inv[k]
  x %= MOD
  x *= fact_inv[n-k]
  x %= MOD
  return x

fact = [1]*(U+1)
fact_inv = [1]*(U+1)
make_fact(fact,fact_inv)

# 重複の起きる場所の間隔だけが問題
n = int(input())
A = [int(x) for x in input().split()]

memo = dict()
d = 0
for i,x in enumerate(A):
  if x in memo:
    d = i - memo[x]
    break
  memo[x] = i

rest = n-d

for k in range(1,n+2):
  ans = comb(n+1,k) - comb(rest,k-1)
  ans %= MOD
  print(ans)
Buggy python submission (verdict: Time Limit Exceeded):
import sys
input = sys.stdin.readline

import itertools

"""
(a_i+1,a_{i+1}] に x がある間は...使う。傾き-1
a_{i+1} -> a_{i+1} + 1 のところでがくっと下がる
そこからa_iまでは傾き0
""" 

N,M = map(int,input().split())
A = [int(x) for x in input().split()]
FROM = A[:-1]
TO = A[1:]

d_slope = [0] * (M+1) # 傾きの差分

"""
5,4,3,2,1,5,5,5,5
0,-1,-1,-1,-1,4,0,0,0
0,-1,0,0,0,0,5,-4,0,0
"""

for x,y in zip(FROM,TO):
    if y < x:
        y += M
    z = y - x
    if z == 1:
        continue
    d_slope[1+(x+1)%M] += -1
    d_slope[1+y%M] += z # 1回で行けたのがz回かかるようになる
    d_slope[1+(y+1)%M] += 1-z

slope = list(itertools.accumulate(d_slope))
slope = [x - sum(slope)//M for x in slope]
slope[0] = 0

# 1番をお気に入りにしたときのスコアを求める
cnt = 0
for x,y in zip(FROM,TO):
    if x < y:
        cnt += (y-x)
    else:
        cnt += y

cnt

answer = cnt + min(itertools.accumulate(slope[2:]))
print(answer)

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

"""
(a_i+1,a_{i+1}] に x がある間は...使う。傾き-1
a_{i+1} -> a_{i+1} + 1 のところでがくっと下がる
そこからa_iまでは傾き0
""" 

N,M = map(int,input().split())
A = [int(x) for x in input().split()]
FROM = A[:-1]
TO = A[1:]

d_slope = [0] * (M+1) # 傾きの差分

"""
5,4,3,2,1,5,5,5,5
0,-1,-1,-1,-1,4,0,0,0
0,-1,0,0,0,0,5,-4,0,0
"""

for x,y in zip(FROM,TO):
    if y < x:
        y += M
    z = y - x
    if z == 1:
        continue
    d_slope[1+(x+1)%M] += -1
    d_slope[1+y%M] += z # 1回で行けたのがz回かかるようになる
    d_slope[1+(y+1)%M] += 1-z

slope = list(itertools.accumulate(d_slope))
S = sum(slope)
slope = [x - S//M for x in slope]
slope[0] = 0

# 1番をお気に入りにしたときのスコアを求める
cnt = 0
for x,y in zip(FROM,TO):
    if x < y:
        cnt += (y-x)
    else:
        cnt += y

answer = cnt - slope[1] + min(itertools.accumulate(slope[1:]))
print(answer)
Buggy python submission (verdict: Runtime Error):
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
A = sorted(map(int, readline().split()))

def main(A):
    N = len(A)
    if A[0] == A[-1]:
        raise
        x = A[0]
        return x == N - 1 or 2 * x <= N
    if A[0] + 1 != A[-1]:
        return False
    a, b = A[0], A[-1]
    full = b
    unique = sum(x == a for x in A)
    return N - unique >= 2 * a

print('Yes' if main(A) else 'No')

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

from collections import Counter

N = int(input())
A = [int(x) for x in input().split()]

x = min(A)
y = max(A)

if x == y:
    # 全員がnon-uniqueな色 or 全員がuniqueな色
    bl = (x <= N//2) or (x == N-1)
elif y != x + 1:
    bl = False
else:
    a = A.count(x)
    b = A.count(y)
    # a人：unique color
    # b人：non-unique color
    # b人でc種類あるとする
    c = y - a
    bl = (1 <= c <= b//2)

answer = 'Yes' if bl else 'No'
print(answer)
Buggy python submission (verdict: Runtime Error):
a,b = map(input().split())
x = a+b
print('error' if x >= 10 else x)

Fixed submission:
a,b = map(int,input().split())
x = a+b
print('error' if x >= 10 else x)