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

Fixed submission:
n = int(input())
_s = input()
q = int(input())
query = [input() for _ in range(q)]

def bitsum(_bit, i):
    s = 0
    while i > 0:
        s += _bit[i]
        i -= i & (-i)
    return s

def bitadd(_bit, i, x):
    while i <= n:
        _bit[i] += x
        i += i & (-i)
    return _bit

al = [chr(ord('a') + i) for i in range(26)]
al_to_idx = dict()
for i in range(26):
    al_to_idx[al[i]] = i

s = list(_s)

# init
import math
n_ = int(math.log(n) / math.log(2)) + 1
bit = [[0] * (2 ** n_ + 1) for _ in range(26)]
for i in range(n):
    idx = al_to_idx[s[i]]
    bit[idx] = bitadd(bit[idx], i + 1, 1)
# print(bit)

for i in range(q):
    _query = query[i].split(' ')
    if _query[0] == '1':
        # decrement old
        idx = al_to_idx[s[int(_query[1]) - 1]]
        bit[idx] = bitadd(bit[idx], int(_query[1]), -1)

        s[int(_query[1]) - 1] = _query[2]
        # print(s)

        # increment
        idx = al_to_idx[_query[2]]
        bit[idx] = bitadd(bit[idx], int(_query[1]), 1)

    else:
        _ans = 0
        for idx in range(26):
            _bit = bit[idx]
            c = bitsum(_bit, int(_query[2])) - bitsum(_bit, int(_query[1]) - 1)
            if c != 0:
                _ans += 1
        print(_ans)

Buggy submission (verdict: Runtime Error):
n = int(input())
_s = input()
q = int(input())
query = [input() for _ in range(q)]

def bitsum(_bit, i):
    s = 0
    while i > 0:
        s += _bit[i]
        i -= i & (-i)
    return s

def bitadd(_bit, i, x):
    while i <= n:
        _bit[i] += x
        i += i & (-i)
    return _bit

al = [chr(ord('a') + i) for i in range(26)]
al_to_idx = dict()
for i in range(26):
    al_to_idx[al[i]] = i

s = list(_s).copy()

# init
import math
n_ = int(math.log2(n)) + 1
bit = [[0] * (2 ** n_ + 1) for _ in range(26)]
for i in range(n):
    idx = al_to_idx[s[i]]
    bit[idx] = bitadd(bit[idx], i + 1, 1)
# print(bit)

for i in range(q):
    _query = query[i].split(' ')
    if _query[0] == '1':
        # decrement old
        idx = al_to_idx[s[int(_query[1]) - 1]]
        bit[idx] = bitadd(bit[idx], int(_query[1]), -1)

        s[int(_query[1]) - 1] = _query[2]
        # print(s)

        # increment
        idx = al_to_idx[_query[2]]
        bit[idx] = bitadd(bit[idx], int(_query[1]), 1)

    else:
        _ans = 0
        for idx in range(26):
            _bit = bit[idx]
            c = bitsum(_bit, int(_query[2])) - bitsum(_bit, int(_query[1]) - 1)
            if c != 0:
                _ans += 1
        print(_ans)
Problem p02948 (python)

Fixed submission:
n, m = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(n)]

import heapq
import collections

a_all = []
for i in range(n):
    a_all.append(ab[i][0])

key_all = list(set(a_all))
key_all.sort()

d = dict()
for k in key_all:
    d[k] = []

for i in range(n):
    a = ab[i][0]
    b = ab[i][1]
    d[a].append(b)

ans = 0
l = []
for i in range(1, m+1):
    if key_all != []:
        if i == key_all[0]:
            for v in d[i]:
                heapq.heappush(l, -1 * v)

            heapq.heappop(key_all)

    if l != []:
        ans += heapq.heappop(l) * -1

print(ans)

Buggy submission (verdict: Runtime Error):
n, m = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(n)]

d = dict()
for i in range(1, m+1):
    d[i] = []

for i in range(n):
    a = ab[i][0]
    b = ab[i][1]

    d[a].append(b)


ans = 0
l = []
import bisect

for i in range(1, m+1):
    for v in d[i]:
        bisect.insort(l, v)

    # print(l)

    if l != []:
        ans += l[-1]
        l.pop()
print(ans)
Problem p03127 (python)

Fixed submission:
from fractions import gcd
from functools import reduce

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

print(reduce(gcd, a))

Buggy submission (verdict: Runtime Error):
from fractions import gcd

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

print(gcd(a))
Problem p03221 (python)

Fixed submission:
n, m = map(int, input().split())
pd = [list(map(int, input().split())) for _ in range(m)]

from collections import defaultdict
dict = defaultdict(list)
for i, (p, d) in enumerate(pd):
    dict[p].append((d, i))

ans = ['' for _ in range(m)]
for key in dict:
    v = dict[key]
    v.sort()

    for i, (y, idx) in enumerate(v):
        tmp = str(key).zfill(6) + str(i + 1).zfill(6)
        ans[idx] = tmp

for a in ans:
    print(a)

Buggy submission (verdict: Runtime Error):
import numpy as np

n, m = list(map(int, input().split()))
py = np.array([list(map(int, input().split())) for _ in range(m)])

py = np.array(py)
order = np.argsort(py[:, 1])
argsorted = py[order]

count_below_same_class = []
visited = dict()
visited_keys = []
for i in range(m):
    p = argsorted[i, 0]
    if p not in visited_keys:
        count_below_same_class.append(0)
        visited[p] = 0
        visited_keys.append(p)
    else:
        count_below_same_class.append(visited[p] + 1)
        visited[p] += 1

inv_order = np.argsort(order)

for i in range(m):
    first = str(py[i, 0]).zfill(6)
    second = str(count_below_same_class[inv_order[i]] + 1).zfill(6)
    print(first + second)
Problem p03326 (python)

Fixed submission:
N, M = map(int, input().split())
x = [list(map(int, input().split())) for _ in range(N)]


import numpy as np
y = np.array(x)

y1 = np.copy(y)
y1[:, 0] = y1[:, 0] * -1

y2 = np.copy(y)
y2[:, 0] = y2[:, 0] * -1
y2[:, 1] = y2[:, 1] * -1

y3 = np.copy(y)
y3[:, 0] = y3[:, 0] * -1
y3[:, 1] = y3[:, 1] * -1
y3[:, 2] = y3[:, 2] * -1

y4 = np.copy(y)
y4[:, 1] = y4[:, 1] * -1

y5 = np.copy(y)
y5[:, 1] = y5[:, 1] * -1
y5[:, 2] = y5[:, 2] * -1

y6 = np.copy(y)
y6[:, 2] = y6[:, 2] * -1

y7 = np.copy(y)
y7[:, 0] = y7[:, 0] * -1
y7[:, 2] = y7[:, 2] * -1

if M != 0:
    print(np.max([np.sum(np.sort(np.sum(y, axis=1))[-1 * M:]),
                 np.sum(np.sort(np.sum(y1, axis=1))[-1 * M:]),
                 np.sum(np.sort(np.sum(y2, axis=1))[-1 * M:]),
                 np.sum(np.sort(np.sum(y3, axis=1))[-1 * M:]),
                 np.sum(np.sort(np.sum(y4, axis=1))[-1 * M:]),
                 np.sum(np.sort(np.sum(y5, axis=1))[-1 * M:]),
                 np.sum(np.sort(np.sum(y6, axis=1))[-1 * M:]),
                 np.sum(np.sort(np.sum(y7, axis=1))[-1 * M:])]))
else:
    print(0)

Buggy submission (verdict: Runtime Error):
N, M = map(int, input().split())
x = [list(map(int, input().split())) for _ in range(N)]


import numpy as np
y = np.array(x)

y1 = np.copy(y)
y1[:, 0] = y1[:, 0] * -1

y2 = np.copy(y)
y2[:, 0] = y2[:, 0] * -1
y2[:, 1] = y2[:, 1] * -1

y3 = np.copy(y)
y3[:, 0] = y3[:, 0] * -1
y3[:, 1] = y3[:, 1] * -1
y3[:, 2] = y3[:, 2] * -1

y4 = np.copy(y)
y4[:, 1] = y4[:, 1] * -1

y5 = np.copy(y)
y5[:, 1] = y5[:, 1] * -1
y5[:, 2] = y5[:, 2] * -1

y6 = np.copy(y)
y6[:, 2] = y6[:, 2] * -1

y7 = np.copy(y)
y7[:, 0] = y7[:, 0] * -1
y7[:, 2] = y7[:, 2] * -1


print(np.max([np.sum(np.sort(np.sum(y, axis=1))[-1 * M:]),
             np.sum(np.sort(np.sum(y1, axis=1))[-1 * M:]),
             np.sum(np.sort(np.sum(y2, axis=1))[-1 * M:]),
             np.sum(np.sort(np.sum(y3, axis=1))[-1 * M:]),
             np.sum(np.sort(np.sum(y4, axis=1))[-1 * M:]),
             np.sum(np.sort(np.sum(y5, axis=1))[-1 * M:]),
             np.sum(np.sort(np.sum(y6, axis=1))[-1 * M:]),
             np.sum(np.sort(np.sum(y7, axis=1))[-1 * M:])]))
Problem p03634 (python)

Fixed submission:
n = int(input())
abc = [list(map(int, input().split())) for _ in range(n - 1)]
Q, K = map(int, input().split())
xy = [list(map(int, input().split())) for _ in range(Q)]

from heapq import heappop, heappush

def main():
    cost = [[] for _ in range(n)]
    for i in range(n - 1):
        a = abc[i][0] - 1
        b = abc[i][1] - 1
        c = abc[i][2]
        cost[a].append((b, c))
        cost[b].append((a, c))
    # print(cost)

    start = K - 1
    d = [float('inf') for i in range(n)] # 最短距離
    d[start] = 0

    q = [] # min-heap, (距離, 頂点)
    heappush(q, (d[start], start))
    while q:
        du, u = heappop(q) # 最短距離とその頂点
        if d[u] < du:
            continue
        for v, weight in cost[u]:
            alt = du + weight
            if d[v] > alt:
                d[v] = alt
                heappush(q, (alt, v))

    for goal1, goal2 in xy:
        print(d[goal1 - 1] + d[goal2 - 1])

if __name__ == '__main__':
    main()

Buggy submission (verdict: Runtime Error):
n = int(input())
abc = [list(map(int, input().split())) for _ in range(n - 1)]
Q, K = map(int, input().split())
xy = [list(map(int, input().split())) for _ in range(Q)]

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

def main():
    cost = [[0] * n for _ in range(n)]

    for i in range(len(abc)):
        a = abc[i][0] - 1
        b = abc[i][1] - 1
        c = abc[i][2]
        cost[a][b] = c

    graph = csr_matrix(cost)
    dist_matrix = dijkstra(csgraph=graph, directed=False, indices=K-1, return_predecessors=False)

    for goal1, goal2 in xy:
        print(d[goal1 - 1] + d[goal2 - 1])

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

Fixed submission:
n, ma, mb = map(int, input().split())
abc = [list(map(int, input().split())) for _ in range(n)]

m = n * 10 + 1

dp = [[[float('inf')] * m for j in range(m)] for i in range(n + 1)]
for i in range(n + 1):
    dp[i][0][0] = 0

for i in range(n):
    for j in range(m):
        for k in range(m):
            dp[i+1][j][k] = min(dp[i+1][j][k], dp[i][j][k])

            # i個目を買う
            jj = j + abc[i][0]
            kk = k + abc[i][1]
            if jj < m and kk < m:
                dp[i+1][jj][kk] = min(dp[i+1][jj][kk], dp[i][j][k] + abc[i][2])

from fractions import gcd
ans = float('inf')
for i in range(1, m):
    for j in range(1, m):
        g = gcd(i, j)
        if i // g == ma and j // g == mb:
            ans = min(ans, dp[-1][i][j])

if ans == float('inf'):
    print(-1)
else:
    print(ans)

Buggy submission (verdict: Runtime Error):
n, ma, mb = map(int, input().split())
abc = [list(map(int, input().split())) for _ in range(n)]

m = n * 10 + 1

dp1 = [[float('inf')] * m for i in range(n + 1)]
for i in range(n + 1):
    dp1[i][0] = 0
for i in range(n):
    for j in range(m):
        dp1[i+1][j] = min(dp1[i+1][j], dp1[i][j])
        # i個目を買う
        jj = j + abc[i][0]
        if jj <= 400:
            dp1[i+1][jj] = min(dp1[i+1][jj], dp1[i][j] + abc[i][2])

dp2 = [[float('inf')] * m for i in range(n + 1)]
for i in range(n + 1):
    dp2[i][0] = 0
for i in range(n):
    for j in range(m):
        dp2[i+1][j] = min(dp2[i+1][j], dp2[i][j])
        # i個目を買う
        jj = j + abc[i][1]
        if jj <= 400:
            dp2[i+1][jj] = min(dp2[i+1][jj], dp2[i][j] + abc[i][2])

from fractions import gcd
ans = float('inf')
for i in range(1, m):
    for j in range(1, m):
        d1 = dp1[-1][i]
        d2 = dp2[-1][j]
        g = gcd(i, j)
        if i // g == ma and j // g == mb:
            ans = min(ans, d1 + d2)

if ans == float('inf'):
    print(-1)
else:
    print(ans)
Problem p03104 (python)

Fixed submission:
def tobin(n):
    return bin(n)[2:][::-1]

def occur(n, i):
    if i >= len(n):
        return 0
    if n[i] == '1':
        if i == 0:
            o = 1
        else:
            o = int(n[:i][::-1], 2) + 1
    else:
        o = 0
    if i < len(n) - 1:
        o += int(n[i+1:][::-1], 2) * (2 ** i)
    return o

A, B = map(int, input().split())
A, B = tobin(A-1 if A > 0 else 0), tobin(B)
F = ""

for i in range(len(B)):
    F += str((occur(B, i) - occur(A, i)) % 2)

print(int(F[::-1], 2))

Buggy submission (verdict: Runtime Error):
def tobin(n):
    return bin(n)[2:][::-1]

def occur(n, i):
    if i >= len(n):
        return 0
    if n[i] == '1':
        if i == 0:
            o = 1
        else:
            o = int(n[:i][::-1], 2) + 1
    else:
        o = 0
    if i < len(n) - 1:
        o += int(n[i+1:][::-1], 2) * (2 ** i)
    return o

A, B = map(int, input().split())
A, B = tobin(A-1), tobin(B)
F = ""

for i in range(len(B)):
    F += str((occur(B, i) - occur(A, i)) % 2)

print(int(F[::-1], 2))
Problem p02725 (python)

Fixed submission:
K, N = list(map(int, input().split()))
A = list(map(int, input().split()))
A = sorted(A)
B = [0 for i in range(N)]
for i in range(N-1):
  B[i] = A[i + 1] - A[i]
B[N - 1] = K - A[N - 1] + A[0]
ans = K - max(B)
print(ans)

Buggy submission (verdict: Runtime Error):
K, N = list(map(int, input().split()))
A = list(map(int, input().split()))
A = sorted(A)
B = [0 for i in range(N)]
for i in range(N-1):
  B[i] = A[i + 1] - A[i]
B[N - 1] = N - A[N - 1] + a[0]
ans = N - max(B)
print(ans)

Buggy submission (verdict: Runtime Error):
K, N = list(map(int, input().split()))
A = list(map(int, input().split()))
A = sorted(A)
B = [0 for i in range(N)]
for i in range(N-1):
  B[i] = A[i + 1] - A[i]
B[N - 1] = N - A[N] + a[0]
ans = N - max(B)
print(ans)
Problem p02984 (python)

Fixed submission:
import sys
import numpy as np
input = sys.stdin.readline
N = int(input())
A = np.array(list(map(int, input().split())))
sgn = np.tile(np.array([1, -1]), N // 2)
sgn = np.concatenate([sgn, np.array([1])])
ans = np.empty(N, dtype=np.int)
ans[0] = (A * sgn).sum()
for i in range(1, N):
    ans[i] = 2 * A[i - 1] - ans[i - 1]
print(*ans)

Buggy submission (verdict: Runtime Error):
import numpy as np
N = int(input())
A = np.array(list(map(int, input().split())))
B = np.zeros((N, N))
for i, b in enumerate(B):
    b[i:i + 2] = 1 / 2
    if i == len(b) - 1:
        b[0] = 1 / 2
x = np.linalg.solve(B, A).astype(np.int)
print(" ".join(map(str, list(x))))
Problem p02987 (python)

Fixed submission:
import numpy as np
S = input()
S_ = list(set(S))
S = np.array(list(S))
S_ = np.array(S_)
ans = 'Yes'
if len(S_)!=2:
    ans = 'No'
elif sum(S==S_[0])!=2:
    ans = 'No'

print(ans)

Buggy submission (verdict: Runtime Error):
import re
import numpy as np
from scipy.sparse import lil_matrix, csr_matrix

N, M = [int(i) for i in re.split(" ", input())]
G = lil_matrix((N, N), dtype=np.bool)

for i in range(M):
    u, v = [int(i) for i in re.split(" ", input())]
    G[u-1, v-1] = True
G = G.tocsr()
G = G.dot(G).dot(G)

S, T = [int(i) for i in re.split(" ", input())]

count = -1
G_tmp = G
for i in range(1, N+1):
    if i == 1:
        pass
    else:
        G_tmp = G_tmp.dot(G)
    if G_tmp[S-1, T-1]:
        count = i
        break

print(count)
Problem p03041 (python)

Fixed submission:
N, K = map(int, input().split())
S = input()
K -= 1
print(S[:K] + {'A': 'a', 'B': 'b', 'C': 'c'}[S[K]] + (S[K+1:] if K+1 < N else ''))

Buggy submission (verdict: Runtime Error):
N, K = map(int, input().split())
S = input()

print(S[:K] + {'A': 'a', 'B': 'b', 'C': 'c'}[S[K]] + (S[K+1:] if K+1 < N else ''))

Buggy submission (verdict: Runtime Error):
N, K = map(int, input().split())
S = input()

print(S[1:K] + {'A': 'a', 'B': 'b', 'C': 'c'}[S[K]] + (S[K+1:] if K+1 < N else ''))
Problem p03055 (python)

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


def farthest(s):
	visited = [False] * N
	stack = [(s, 0)]
	best = s, 0
	while stack:
		i, d = stack.pop()
		visited[i] = True
		if best[1] < d:
			best = i, d
		stack.extend((v, d + 1) for v in E[i] if not visited[v])
	return best

print('First' if (farthest(farthest(0)[0])[1] % 3 != 1) else 'Second')

Buggy submission (verdict: Runtime Error):
import numpy as np

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


INF = N + 1
D = [INF] * N

stack = [
	i
	for i in range(N)
	if len(E[i]) == 1
]

for i in stack:
	D[i] = 0

max_d = 0
cnt = 0
while stack:
	nexts = []
	for i in stack:
		if D[i] > max_d:
			D[i] = max_d
		nexts.extend(v for v in E[i] if D[v] == INF)
	max_d += 1
    cnt = len(stacks)
	stack = nexts

Rx2 = max_d * 2 if 1 < cnt else max_d * 2 - 1
print('First' if (Rx2 % 3 != 2) else 'Second')
Problem p02948 (python)

Fixed submission:
import heapq

N,M = map(int,input().split())
AB = [list(map(int,input().split())) for _ in range(N)]


d_AB = {a:[] for a,b in AB}
for a,b in AB:
    d_AB[a].append(-b)
#print(d_AB)
H = []
heapq.heapify(H)
money = 0
for i in range(1,M+1):
    if i in d_AB.keys():
        for ab in d_AB[i]:
            heapq.heappush(H,ab)
        #print(H)
        money += heapq.heappop(H)
        #print(money)
        
    else:
        money += heapq.heappushpop(H,0)

print(-money)

Buggy submission (verdict: Runtime Error):
import heapq

N,M = map(int,input().split())
AB = [list(map(int,input().split())) for _ in range(N)]


d_AB = {a:[] for a,b in AB}
for a,b in AB:
    d_AB[a].append(-b)

H = [0]
money = 0
for i in range(1,M+1):
    if i in d_AB.keys():
        H += d_AB[i]
    #else:
        #H += [0]
    #print(H)
    heapq.heapify(H)
    money += heapq.heappop(H)

print(-money)
Problem p02863 (python)

Fixed submission:
import sys
from operator import itemgetter


def main():
    input = sys.stdin.readline
    N, T = map(int, input().strip().split())
    foods = sorted([list(map(int, input().strip().split())) for _ in range(N)], key=itemgetter(0))

    ans = 0
    dp = [[0] * (T+1) for _ in range(N+1)]
    for j, food in enumerate(foods):
        n_a, n_b = food
        for k in range(T+1):
            if k == T:
                dp[j+1][k] = max(dp[j][k], dp[j][k-1]+n_b)
            elif k < n_a:
                dp[j+1][k] = dp[j][k]
            else:
                dp[j+1][k] = max(dp[j][k], dp[j][k-n_a]+n_b)
        #print(dp[j+1])
    ans = dp[-1][-1]
    print(ans)

if __name__ == "__main__":
    main()

Buggy submission (verdict: Runtime Error):
import sys
from operator import itemgetter


def main():
    input = sys.stdin.readline
    N, T = map(int, input().strip().split())
    foods = sorted([(map(int, input().strip().split())) for _ in range(N)], key=itemgetter(0))

    ans = 0
    dp = [[0] * (T+1) for _ in range(N+1)]
    for j, food in enumerate(foods):
        n_a, n_b = food
        for k in range(T+1):
            if k == T:
                dp[j+1][k] = max(dp[j][k], dp[j][k-1]+n_b)
            elif k < n_a:
                dp[j+1][k] = dp[j][k]
            else:
                dp[j+1][k] = max(dp[j][k], dp[j][k-n_a]+n_b)
        #print(dp[j+1])
    ans = dp[-1][-1]
    print(ans)

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

Fixed submission:
from bisect import bisect_left
from operator import itemgetter

N, Q = map(int, input().split(" "))
check_points = [tuple(map(int, input().split(" "))) for _ in range(N)]
querys = [int(input()) for _ in range(Q)]
time = [-1 for _ in range(Q)]
jump = [-1 for _ in range(Q)]
check_points = sorted(check_points, key=itemgetter(2))
b_left = bisect_left

for line in check_points:
    s, f, x = line
    start = s-x
    end = f-x
    left = b_left(querys, start)
    right = b_left(querys, end)
    while left < right:
        if time[left] == -1:
            time[left] = x
            jump[left] = right
            left += 1
        else:
            left = jump[left]

for t in time:
    print(t)

Buggy submission (verdict: Runtime Error):
from bisect import bisect_left
from operator import itemgetter

input = sys.stdin.readline

N, Q = map(int, input().split(" "))
check_points = [tuple(map(int, input().split(" "))) for _ in range(N)]
querys = [int(input()) for _ in range(Q)]
time = [-1] * Q
jump = [-1] * Q
check_points = sorted(check_points, key=itemgetter(2))
b_left = bisect_left

for line in check_points:
    s, f, x = line
    start = s-x
    end = f-x
    left = b_left(querys, start)
    right = b_left(querys, end)
    while left < right:
        if time[left] == -1:
            time[left] = x
            jump[left] = right
            left += 1
        else:
            left = jump[left]

for t in time:
    print(t)
Problem p03038 (python)

Fixed submission:
from operator import itemgetter

N, M = map(int, input().split(" "))
A = list(map(int, input().split(" ")))
BC = [list(map(int, input().split(" "))) for _ in range(M)]

A = sorted(A)
BC = sorted(BC, key=itemgetter(1), reverse=True)
now = 0
count = 0
flag = False

for b, c in BC:
    while True:
        # print(A[now], c)
        if A[now] >= c:
            flag = True
            break
        count += c-A[now]
        b -= 1
        now += 1
        if now >= N:
            flag = True
            break
        if b <= 0:
            break
    if flag:
        break
print(sum(A) + count)

Buggy submission (verdict: Runtime Error):
from operator import itemgetter

N, M = map(int, input().split(" "))
A = list(map(int, input().split(" ")))
BC = [list(map(int, input().split(" "))) for _ in range(M)]

A = sorted(A)
BC = sorted(BC, key=itemgetter(1), reverse=True)
now = 0
count = 0
flag = False

for b, c in BC:
    while True:
        # print(A[now], c)
        if A[now] >= c:
            break
            flag = True
        count += c-A[now]
        b -= 1
        now += 1
        if now >= N:
            break
            flag = True
        if b <= 0:
            break
    if flag:
        break
print(sum(A) + count)

Buggy submission (verdict: Runtime Error):
from operator import itemgetter

N, M = map(int, input().split(" "))
A = list(map(int, input().split(" ")))
BC = [list(map(int, input().split(" "))) for _ in range(M)]

A = sorted(A)
BC = sorted(BC, key=itemgetter(1), reverse=True)
now = 0
count = 0
flag = False

for b, c in BC:
    while True:
        # print(A[now], c)
        if A[now] >= c:
            break
            flag = True
        count += c-A[now]
        b -= 1
        now += 1
        if b <= 0:
            break
        if now >= N:
            break
    if flag:
        break
print(sum(A) + count)
Problem p03291 (python)

Fixed submission:
def calc_ABC(a, c, bq, aq):
    ans = 0
    if aq != 0:
        if bq != 0:
            ans = ans + (a*pow(3, bq, MOD) + bq*pow(3, bq-1, MOD)) \
                 * (c*pow(3, aq, MOD) + aq*pow(3, (aq-1), MOD))
        else:
            ans = ans + (a*pow(3, bq, MOD)) \
                 * (c*pow(3, aq, MOD) + aq*pow(3, (aq-1), MOD))
    else:
        if bq != 0:
            ans = ans + (a*pow(3, bq, MOD) + bq*pow(3, bq-1, MOD)) \
                 * (c*pow(3, aq, MOD))
        else:
            ans = ans + (a*pow(3, bq, MOD)) \
                 * (c*pow(3, aq, MOD))
    return ans % MOD


MOD = 10**9 + 7
S = input()
ans = 0
count_a = 0
count_c = S.count('C')
count_afterq = S.count('?')
count_beforeq = 0

for i in range(len(S)):
    if S[i] == 'A':
        count_a += 1
    elif S[i] == 'B':
        ans += calc_ABC(count_a, count_c, count_beforeq, count_afterq)
        ans = ans % MOD
    elif S[i] == 'C':
        count_c -= 1
    elif S[i] == '?':
        count_afterq -= 1
        ans += calc_ABC(count_a, count_c, count_beforeq, count_afterq)
        ans = ans % MOD
        count_beforeq += 1
print(ans)

Buggy submission (verdict: Runtime Error):
def calc_ABC(a, c, bq, aq):
    ans = 0
    if aq != 0:
        if bq != 0:
            ans = ans + (a*pow(3, bq, MOD) + bq*pow(3, bq-1, MOD)) \
                 * (c*pow(3, aq, MOD) + aq*pow(3, (aq-1), MOD))
        else:
            ans = ans + (a*pow(3, bq, MOD)) \
                 * (c*pow(3, aq, MOD) + aq*pow(3, (aq-1), MOD))
    else:
        if bq != 0:
            ans = ans + (a*pow(3, bq, MOD) + bq*pow(3, bq-1, MOD)) \
                 * (c*pow(3, aq, MOD))
        else:
            ans = ans + (a*pow(3, bq, MOD)) \
                 * (c*pow(3, aq, MOD))
    return ans % MOD


MOD = 10**9 + 7
S = raw_input()
ans = 0
count_a = 0
count_c = S.count('C')
count_afterq = S.count('?')
count_beforeq = 0

for i in range(len(S)):
    if S[i] == 'A':
        count_a += 1
    elif S[i] == 'B':
        ans += calc_ABC(count_a, count_c, count_beforeq, count_afterq)
        ans = ans % MOD
    elif S[i] == 'C':
        count_c -= 1
    elif S[i] == '?':
        count_afterq -= 1
        ans += calc_ABC(count_a, count_c, count_beforeq, count_afterq)
        ans = ans % MOD
        count_beforeq += 1
print(ans)