MOD = 1000000007
N = 100001

fibo = [1, 1] + [0] * N
for i in range(2, N):
    fibo[i] = (fibo[i - 1] + fibo[i - 2]) % MOD

n, m = list(map(int, input().split(" ")))
a_list = [int(input()) for _ in range(m)]
ngs = [i in a_list for i in range(n)]
ngs.append(False)
for i in range(n):
    if ngs[i] and ngs[i + 1]:
        print(0)
        exit()
cnts = []
cnt = 0

for ng in ngs:
    if ng:
        cnts.append(cnt)
        cnt = 0
        continue
    cnt += 1
cnts.append(cnt)
ans = 1
for c in cnts:
    if c != 0:
        ans *= fibo[c - 1]
# print(ngs)
# print(cnts)
print(ans % MOD)

MOD = 1000000007
N = 100001

fibo = [1, 1] + [0] * N
for i in range(2, N):
    fibo[i] = (fibo[i - 1] + fibo[i - 2]) % MOD

n, m = list(map(int, input().split(" ")))
a_list = [int(input()) for _ in range(m)]
is_ngs = [0] * (n + 2)
for a in a_list:
    is_ngs[a] = 1
for i in range(n):
    if is_ngs[i] and is_ngs[i + 1]:
        print(0)
        exit()
cnts = []
cnt = 0

for i in range(n + 1):
    if is_ngs[i]:
        cnts.append(cnt)
        cnt = 0
        continue
    cnt += 1
cnts.append(cnt)
ans = 1
for c in cnts:
    if c != 0:
        ans *= fibo[c - 1]
# print(is_ngs)
# print(cnts)
print(ans % MOD)


def main():
    N, M = map(int, input().split())
    A = [int(input()) for _ in range(M)]
    dp = [0] * (N + 2)
    dp[-2] = 1
    for i in range(N - 1, -1, -1):
        if i in A:
            continue
        elif i + 1 in A:
            dp[i] = dp[i + 2]
        elif i + 2 in A:
            dp[i] = dp[i + 1]
        elif i + 1 in A and i + 2 in A:
            break
        else:
            dp[i] = dp[i + 1] + dp[i + 2]
    print(dp[0] % 1000000007)

main()

def main():
    N, M = map(int, input().split())
    A = [0] * (N + 2)
    for _ in range(M):
        A[int(input())] = 1
    dp = [0] * (N + 2)
    dp[-2] = 1
    for i in range(N - 1, -1, -1):
        if A[i] == 1:
            continue
        dp[i] = dp[i + 1] + dp[i + 2]
    print(dp[0] % 1000000007)

main()


n, m = map(int, input().split())
hole_ids = {int(input()) - 1: 0 for _ in range(m)}
X = 1000000007

def solve(n, hole_ids):
    nums = []
    # nums = [0] * n
    for i in range(n):
        if i in hole_ids:
            nums.append(0)
            # nums[i] = 0
            continue

        if i == 0:
            nums.append(1)
            # nums[i] = 1
        elif i == 1:
            # 1つ前から1段上がるから2つ前から2個飛ばし
            nums.append(nums[-1] + 1)
            # nums[i] = nums[i-1] + 1
        else:
            nums.append((nums[-1] % X + nums[-2] % X) % X)
            # nums[i] = (nums[i-1] + nums[i-2]) % X
    return nums[-1]

print(solve(n, hole_ids))
n, m = map(int, input().split())
hole_ids = {int(input()) - 1: 0 for _ in range(m)}
X = 1000000007

def solve(n, hole_ids):
    nums = []
    # nums = [0] * n
    for i in range(n):
        if i in hole_ids:
            nums.append(0)
            # nums[i] = 0
            continue

        if i == 0:
            nums.append(1)
            # nums[i] = 1
        elif i == 1:
            # 1つ前から1段上がるから2つ前から2個飛ばし
            nums.append(nums[-1] + 1)
            # nums[i] = nums[i-1] + 1
        else:
            nums.append((nums[-1] % X + nums[-2] % X) % X)
            # nums[i] = (nums[i-1] + nums[i-2]) % X
    return nums[-1]

print(solve(n, hole_ids))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03013/Python/s744106332.py", line 29, in <module>
    n, m = map(int, input().split())
EOFError: EOF when reading a line


N, M = [int(s) for s in input().split()]
A = []
for _ in range(M):
    A.append(int(input()))

counts = [0] * (N + 1)
for i in range(N + 1):
    if i == 0:
        counts[i] = 1
    elif i == 1:
        if i not in A:
            counts[i] = 1
    else:
        for j in [i - 2, i - 1]:
            if j not in A and i not in A:
                counts[i] += counts[j]
                counts[i] %= 1000000007

print(counts[N])

N, M = [int(s) for s in input().split()]
A = []
for _ in range(M):
    A.append(int(input()))
A = set(A)

counts = [0] * (N + 1)
for i in range(N + 1):
    if i == 0:
        counts[i] = 1
    elif i == 1:
        if i not in A:
            counts[i] = 1
    else:
        if i not in A:
            for j in [i - 2, i - 1]:
                if j not in A:
                    counts[i] += counts[j]
                    counts[i] %= 1000000007

print(counts[N])


import sys

input = sys.stdin.readline

def main():
    H, W = map(int, input().split())
    S = [None] * (H + 2)
    S[0] = S[-1] = "#" * (W + 2)
    for i in range(1, H + 1):
        S[i] = "".join(["#", input().rstrip(), "#"])

    U = [[-1] * (W + 2) for _ in range(H + 2)]
    D = [[-1] * (W + 2) for _ in range(H + 2)]
    L = [[-1] * (W + 2) for _ in range(H + 2)]
    R = [[-1] * (W + 2) for _ in range(H + 2)]
    for h in range(1, H + 1):
        for w in range(1, W + 1):
            if S[h][w] == "#":
                continue
            if U[h][w] == -1:
                U[h][w] = 0
                d = 0
                while True:
                    d += 1
                    if S[h + d][w] == "#":
                        break
                    U[h + d][w] = d
            if L[h][w] == -1:
                L[h][w] = 0
                d = 0
                while True:
                    d += 1
                    if S[h][w + d] == "#":
                        break
                    L[h][w + d] = d

    for h in reversed(range(1, H + 1)):
        for w in reversed(range(1, W + 1)):
            if S[h][w] == "#":
                continue
            if D[h][w] == -1:
                D[h][w] = 0
                d = 0
                while True:
                    d += 1
                    if S[h - d][w] == "#":
                        break
                    D[h - d][w] = d
            if R[h][w] == -1:
                R[h][w] = 0
                d = 0
                while True:
                    d += 1
                    if S[h][w - d] == "#":
                        break
                    R[h][w - d] = d

    ans = 0
    for h in range(1, H + 1):
        for w in range(1, W + 1):
            dist = U[h][w] + D[h][w] + L[h][w] + R[h][w] + 1
            if ans < dist:
                ans = dist

    print(ans)

if __name__ == "__main__":
    main()

import sys

import numba as nb
import numpy as np

input = sys.stdin.readline

@nb.njit("i8(i8,i8,b1[:,:])", cache=True)
def solve(H, W, S):
    U = np.full(shape=(H + 2, W + 2), fill_value=-1, dtype=np.int64)
    D = np.full(shape=(H + 2, W + 2), fill_value=-1, dtype=np.int64)
    L = np.full(shape=(H + 2, W + 2), fill_value=-1, dtype=np.int64)
    R = np.full(shape=(H + 2, W + 2), fill_value=-1, dtype=np.int64)
    for h in range(1, H + 1):
        for w in range(1, W + 1):
            if not S[h][w]:
                continue
            if U[h][w] == -1:
                U[h][w] = 0
                d = 0
                while True:
                    d += 1
                    if not S[h + d][w]:
                        break
                    U[h + d][w] = d
            if L[h][w] == -1:
                L[h][w] = 0
                d = 0
                while True:
                    d += 1
                    if not S[h][w + d]:
                        break
                    L[h][w + d] = d

    for h in range(H + 1, 0, -1):
        for w in range(W + 1, 0, -1):
            if not S[h][w]:
                continue
            if D[h][w] == -1:
                D[h][w] = 0
                d = 0
                while True:
                    d += 1
                    if not S[h - d][w]:
                        break
                    D[h - d][w] = d
            if R[h][w] == -1:
                R[h][w] = 0
                d = 0
                while True:
                    d += 1
                    if not S[h][w - d]:
                        break
                    R[h][w - d] = d

    dist = U + D + L + R + 1
    ans = np.max(dist)
    return ans

def main():
    H, W = map(int, input().split())
    S = np.zeros(shape=(H + 2, W + 2), dtype=np.bool)
    for i in range(1, H + 1):
        S[i][1:-1] = [s == "." for s in input().rstrip()]

    ans = solve(H, W, S)

    print(ans)

if __name__ == "__main__":
    main()


H, W = map(int, input().split())
MAP = [[] for _ in range(H)]
L = [[[] for h in range(W)] for _ in range(H)]
R = [[[] for h in range(W)] for _ in range(H)]
D = [[[] for h in range(W)] for _ in range(H)]
U = [[[] for h in range(W)] for _ in range(H)]

for i in range(H):
    MAP[i] = list(input())

for i in range(H):
    for j in range(W):
        if MAP[i][j] == "#":
            L[i][j] = 0
        elif j == 0:
            L[i][j] = 1
        else:
            L[i][j] = L[i][j - 1] + 1

        if MAP[i][W - j - 1] == "#":
            R[i][W - j - 1] = 0
        elif j == 0:
            R[i][W - j - 1] = 1
        else:
            R[i][W - j - 1] = R[i][W - j] + 1

for j in range(W):
    for i in range(H):
        if MAP[i][j] == "#":
            U[i][j] = 0
        elif i == 0:
            U[i][j] = 1
        else:
            U[i][j] = U[i - 1][j] + 1

        if MAP[H - i - 1][j] == "#":
            D[H - i - 1][j] = 0
        elif i == 0:
            D[H - i - 1][j] = 1
        else:
            D[H - i - 1][j] = D[H - i][j] + 1
result = 0
for i in range(H):
    for j in range(W):
        result = max(result, U[i][j] + D[i][j] + L[i][j] + R[i][j] - 3)

print(result)

H, W = map(int, input().split())
MAP = [list(input()) for _ in range(H)]
L = [[0] * W for _ in range(H)]
R = [[0] * W for _ in range(H)]
D = [[0] * W for _ in range(H)]
U = [[0] * W for _ in range(H)]

for i in range(H):
    for j in range(W):
        if MAP[i][j] == "#":
            L[i][j] = 0
        elif j == 0:
            L[i][j] = 1
        else:
            L[i][j] = L[i][j - 1] + 1

        if MAP[i][W - j - 1] == "#":
            R[i][W - j - 1] = 0
        elif j == 0:
            R[i][W - j - 1] = 1
        else:
            R[i][W - j - 1] = R[i][W - j] + 1

for j in range(W):
    for i in range(H):
        if MAP[i][j] == "#":
            U[i][j] = 0
        elif i == 0:
            U[i][j] = 1
        else:
            U[i][j] = U[i - 1][j] + 1

        if MAP[H - i - 1][j] == "#":
            D[H - i - 1][j] = 0
        elif i == 0:
            D[H - i - 1][j] = 1
        else:
            D[H - i - 1][j] = D[H - i][j] + 1
result = 0
for i in range(H):
    for j in range(W):
        result = max(result, U[i][j] + D[i][j] + L[i][j] + R[i][j] - 3)

print(result)


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

HORIZONTAL = [[0] * w for _ in range(h)]
for i in range(h):
    COUNTS = []
    count = 0
    for j in range(w):
        if GRID[i][j] == ".":
            count += 1
        else:
            COUNTS.append(count)
            count = 0
    COUNTS.append(count)
    k = 0
    for j in range(w):
        if GRID[i][j] == ".":
            HORIZONTAL[i][j] = COUNTS[k]
        else:
            k += 1

VERTICAL = [[0] * w for _ in range(h)]
for j in range(w):
    COUNTS = []
    count = 0
    for i in range(h):
        if GRID[i][j] == ".":
            count += 1
        else:
            COUNTS.append(count)
            count = 0
    COUNTS.append(count)
    k = 0
    for i in range(h):
        if GRID[i][j] == ".":
            VERTICAL[i][j] = COUNTS[k]
        else:
            k += 1

LIGHTED = []
for i in range(h):
    for j in range(w):
        LIGHTED.append(HORIZONTAL[i][j] + VERTICAL[i][j] - 1)

ans = max(LIGHTED)
print(ans)

import sys

input = sys.stdin.readline
import numpy as np

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

GRID = []
for _ in range(h):
    S = [0] + [0 if c == "#" else 1 for c in input().strip()] + [0]
    GRID.append(S)
GRID.insert(0, [0] * (w + 2))
GRID.append([0] * (w + 2))
grid = np.array(GRID)

top = np.zeros((h + 2, w + 2), dtype=np.int)
bottom = np.zeros((h + 2, w + 2), dtype=np.int)
left = np.zeros((h + 2, w + 2), dtype=np.int)
right = np.zeros((h + 2, w + 2), dtype=np.int)

for i in range(1, h + 1):
    top[i] = (top[i - 1] + 1) * grid[i]
for i in range(h, 0, -1):
    bottom[i] = (bottom[i + 1] + 1) * grid[i]
for j in range(1, w + 1):
    left[:, j] = (left[:, j - 1] + 1) * grid[:, j]
for j in range(w, 0, -1):
    right[:, j] = (right[:, j + 1] + 1) * grid[:, j]

column = (top + bottom - 1) * grid
row = (left + right - 1) * grid
lighted = (column + row - 1) * grid

ans = lighted.max()
print(ans)


import numpy as np

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

X = np.zeros((W, H))
for i in range(H):
    start = 0
    cnt = 0
    for j in range(W):
        if s[i][j] == "." and j == W - 1:
            cnt += 1
            for k in range(start, W):
                if s[i][k] == ".":
                    X[i][k] = cnt
        elif s[i][j] == ".":
            cnt += 1
        elif s[i][j] == "#":
            for k in range(start, j):
                if s[i][k] == ".":
                    X[i][k] = cnt
            start = j
            cnt = 0

Y = np.zeros((W, H))
for i in range(W):
    start = 0
    cnt = 0
    for j in range(H):
        if s[j][i] == "." and j == H - 1:
            cnt += 1
            for k in range(start, H):
                if s[k][i] == ".":
                    Y[k][i] = cnt
        elif s[j][i] == ".":
            cnt += 1
        elif s[j][i] == "#":
            for k in range(start, j):
                if s[k][i] == ".":
                    Y[k][i] = cnt
            start = j
            cnt = 0

XY = X + Y - 1
print(int(np.max(XY)))

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

X = [[0] * W for _ in range(H)]
for i in range(H):
    start = 0
    cnt = 0
    for j in range(W):
        if s[i][j] == "." and j == W - 1:
            cnt += 1
            for k in range(start, W):
                if s[i][k] == ".":
                    X[i][k] = cnt
        elif s[i][j] == ".":
            cnt += 1
        elif s[i][j] == "#":
            for k in range(start, j):
                if s[i][k] == ".":
                    X[i][k] = cnt
            start = j
            cnt = 0

Y = [[0] * W for _ in range(H)]
for i in range(W):
    start = 0
    cnt = 0
    for j in range(H):
        if s[j][i] == "." and j == H - 1:
            cnt += 1
            for k in range(start, H):
                if s[k][i] == ".":
                    Y[k][i] = cnt
        elif s[j][i] == ".":
            cnt += 1
        elif s[j][i] == "#":
            for k in range(start, j):
                if s[k][i] == ".":
                    Y[k][i] = cnt
            start = j
            cnt = 0

XY = []
for i in range(H):
    for j in range(W):
        XY.append(X[i][j] + Y[i][j] - 1)

print(max(XY))


from itertools import groupby

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

res = 0
count = [[-1 * int(Ss[i][j] == ".") for j in range(W)] for i in range(H)]
for i in range(H):
    j = 0
    for x in groupby(Ss[i]):
        k = len(list(x[1]))
        for _ in range(k):
            count[i][j] += k * (x[0] == ".")
            j += 1

for j in range(W):
    i = 0
    for x in groupby([Ss[i][j] for i in range(H)]):
        k = len(list(x[1]))
        for _ in range(k):
            new_res = count[i][j] + k * (x[0] == ".")
            if res < new_res:
                res = new_res
            i += 1

print(res)

from itertools import groupby

[H, W] = map(int, input().split())
Ss = [list(map(lambda x: int(x == "."), list(input()))) for _ in range(H)]

res = 0
count = [[-Ss[i][j] for j in range(W)] for i in range(H)]
for i in range(H):
    j = 0
    for x in groupby(Ss[i]):
        k = len(list(x[1]))
        for _ in range(k):
            count[i][j] += k * x[0]
            j += 1

for j in range(W):
    i = 0
    for x in groupby([Ss[i][j] for i in range(H)]):
        k = len(list(x[1]))
        for _ in range(k):
            new_res = count[i][j] + k * x[0]
            if res < new_res:
                res = new_res
            i += 1

print(res)


s = input()
if "BC" in s:
    s = s.replace("BC", "D")
else:
    print(0)
    quit()

pos = 0
str_len = len(s)
count = 0
seq_a = 0
seq_d = 0

while pos < str_len:
    if s[pos] == "A":
        while pos < str_len and s[pos] == "A":
            seq_a += 1
            pos += 1
        if s[pos] == "D":
            while pos < str_len and s[pos] == "D":
                seq_d += 1
                pos += 1
            count += seq_a * seq_d
            if pos < str_len and s[pos] != "A":
                seq_a = 0
            seq_d = 0
        else:
            pos += 1
            seq_a = 0
    else:
        pos += 1
        seq_a = 0

print(count)

s = input()
pos = 0
str_len = len(s)
count = 0
seq_a = 0
seq_bc = 0

while pos < str_len:
    if s[pos] == "A":
        while pos < str_len and s[pos] == "A":
            seq_a += 1
            pos += 1
        if pos + 1 < str_len and s[pos] == "B" and s[pos + 1] == "C":
            while (
                pos < str_len
                and s[pos] == "B"
                and pos + 1 < str_len
                and s[pos + 1] == "C"
            ):
                seq_bc += 1
                pos += 2
            count += seq_a * seq_bc
            if pos < str_len and s[pos] != "A":
                seq_a = 0
            seq_bc = 0
        else:
            pos += 1
            seq_a = 0
    else:
        pos += 1
        seq_a = 0

print(count)


s = input()

# step1: pre-process "BC" を Xに置き換える
tmp = ""
flag = False  # skip用
for i in range(1, len(s)):
    if flag:
        flag = False
        continue
    elif s[i - 1] + s[i] == "BC":
        tmp += "X"
        flag = True
    else:
        tmp += s[i - 1]

if not flag:
    tmp += s[-1]

cnt = 0
ans = 0
# step:2 Xより左側にあるAの数を数える。
# ただし、B、Cが現れると、カウンターリセット
# （そのB、Cを越えてSwapできないため）
for i in range(len(tmp)):
    if tmp[i] == "A":
        cnt += 1
    elif tmp[i] == "B" or tmp[i] == "C":
        cnt = 0
    elif tmp[i] == "X":
        ans += cnt

print(ans)

s = input()

tmp = ""
cnt = 0
ans = 0
flag = False  # skip用
for i in range(0, len(s) - 1):
    if flag:
        flag = False
        continue
    if s[i] == "A":
        cnt += 1
    elif s[i] + s[i + 1] == "BC":
        ans += cnt
        flag = True
    else:
        cnt = 0

print(ans)


s = input()
s = s.replace("BC", "D")

ans = a = 0
for i in s:
    if i == "A":
        a += 1
    elif i == "D":
        ans += a
    else:
        a = 0
print(ans)


def li():
    return list(map(int, input().split()))

if __name__ == "__main__":
    s = input()
    ope_num = 0
    index = 0
    a_stock = 0
    b_stock = 0
    s = list(s)
    while index < len(s):
        # print(s)
        # print(index)
        # print(ope_num)
        # print()
        si = s[index]
        if si == "A":
            if b_stock > 0:
                a_stock = 1
            else:
                a_stock = a_stock + 1
            b_stock = 0
        elif a_stock > 0:
            if b_stock == 0:
                if si == "B":
                    b_stock = 1
                else:
                    a_stock = 0
                    b_stock = 0
            elif si == "C":
                ope_num = ope_num + a_stock
                # s[index - 2 - a_stock + 1] = "B"
                # s[index - 1 - a_stock + 1] = "C"
                for i in range(a_stock - 1, -1, -1):
                    s[index - i] = "A"
                index = index - a_stock
                a_stock = 0
                b_stock = 0
            else:
                a_stock = 0
                b_stock = 0
        else:
            a_stock = 0
            b_stock = 0
        index = index + 1
    print(ope_num)

# ABCの数
# ABCの前にあるAの分だけ追加で操作できる
# ABCの後にある(BC)の分だけ追加で操作できる

# Aがあれば覚えておく
# ABCと来たら、それより前側に隣接しているAの回数だけ追加で操作できる
# 見つかったABCをBCAに置き換える
# BCAのAから走査を継続する

def li():
    return list(map(int, input().split()))

if __name__ == "__main__":
    s = input()
    ope_num = 0
    index = 0
    a_stock = 0
    b_stock = 0
    s = list(s)
    while index < len(s):
        # print(s)
        # print(index)
        # print(ope_num)
        # print()
        si = s[index]
        if si == "A":
            if b_stock > 0:
                a_stock = 1
            else:
                a_stock = a_stock + 1
            b_stock = 0
        elif a_stock > 0:
            if b_stock == 0:
                if si == "B":
                    b_stock = 1
                else:
                    a_stock = 0
                    b_stock = 0
            elif si == "C":
                ope_num = ope_num + a_stock
                # s[index - 2 - a_stock + 1] = "B"
                # s[index - 1 - a_stock + 1] = "C"
                # s[index] = "A"
                # index = index - 1
                a_stock = a_stock
                b_stock = 0
            else:
                a_stock = 0
                b_stock = 0
        else:
            a_stock = 0
            b_stock = 0
        index = index + 1
    print(ope_num)

# ABCの数
# ABCの前にあるAの分だけ追加で操作できる
# ABCの後にある(BC)の分だけ追加で操作できる

# Aがあれば覚えておく
# ABCと来たら、それより前側に隣接しているAの回数だけ追加で操作できる
# 見つかったABCをBCAに置き換える
# BCAのAから走査を継続する


s = input()
ans = 0

while True:
    c = s.count("ABC")
    ans += c
    if c == 0:
        print(ans)
        break
    s = s.replace("ABC", "BCA")

s = input()
s2 = s.replace("BC", "D")
ans = 0
na = 0
for c in s2:
    if na:
        if c == "D":
            ans += na
        elif c != "A":
            na = 0
    if c == "A":
        na += 1
print(ans)


s = input()

ans = 0

check = s.count("ABC")

while check > 0:
    ans += check
    s = s.replace("ABC", "BCA")
    check = s.count("ABC")

print(ans)

import sys

input = sys.stdin.readline

def main():
    s = input().strip()

    ans = 0
    count_a = 0
    if s[0] == "A":
        count_a += 1
    for i in range(len(s) - 1):
        tmp = s[i : i + 2]
        if tmp == "AA":
            count_a += 1
        elif tmp == "AB":
            pass
        elif tmp == "BC":
            ans += count_a
        elif tmp == "CB":
            pass
        elif tmp == "CA":
            count_a += 1
        elif tmp == "BA":
            count_a = 1
        else:
            count_a = 0
        # print(i, count_a)
    print(ans)

if __name__ == "__main__":
    main()


import sys

sys.setrecursionlimit(10000)

def first_dfs(v, p, stones, dists, costs):
    stone = s[v]
    dist = 0
    cost = 0
    children_dists = []
    for u in links[v]:
        if u == p:
            continue
        us, ud, uc = first_dfs(u, v, stones, dists, costs)
        stone += us
        dist += us + ud
        cost += uc
        children_dists.append((us + ud, uc))
    # print(v, p, stone, dist, cost, children_dists)
    if len(children_dists) > 1:
        md, mc = max(children_dists)
        if dist - md < md - mc * 2:
            cost = dist - md + mc
        else:
            cost = dist // 2
        # print(v, p, md, hd, dist, cost)
    stones[v] = stone
    dists[v] = dist
    costs[v] = cost
    return stone, dist, cost

def second_dfs(v, p, pd, pc):
    children_dists = []
    dist = 0

    for u in links[v]:
        if u == p:
            dist += pd
            children_dists.append((pd, pc))
            continue
        ud = stones[u] + dists[u]
        uc = costs[u]
        dist += ud
        children_dists.append((ud, uc))
    # print(v, p, pd, pc, dist, children_dists)

    if len(children_dists) == 1:
        u = next(iter(links[v]))
        second_dfs(u, v, s[v], 0)
        return

    children_dists.sort(reverse=True)
    md1, mc1 = children_dists[0]
    md2, mc2 = children_dists[1]

    hd, m = divmod(dist, 2)
    # print(' ', hd, m, md1, mc1)
    if m == 0 and dist - md1 >= md1 - mc1 * 2:
        print(hd)
        exit()

    for u in links[v]:
        if u == p:
            continue
        us = stones[u]
        ud = dists[u]
        uc = costs[u]
        usd = us + ud
        if usd > 0:
            if usd == md1 and uc == mc1:
                md, mc = md2, mc2
            else:
                md, mc = md1, mc1
            td = dist - usd
            if td - md < md - mc * 2:
                vc = td - md + mc
            else:
                vc = td // 2
            second_dfs(u, v, td + (all_stones - us), vc)

n = int(input())
s = list(map(int, input()))
links = [set() for _ in [0] * n]
for line in sys.stdin:
    a, b = map(int, line.split())
    a -= 1
    b -= 1
    links[a].add(b)
    links[b].add(a)
all_stones = sum(s)
if all_stones == 1:
    print(0)
    exit()
# print(links)
stones = [0] * n  # 1を根とした木の、頂点vの部分木以下（自身含む）にある石の数
dists = [0] * n  # 頂点vの部分木以下にある石 x それぞれのvとの距離 の和
costs = [0] * n  # 頂点v以下同士の石で、最大限頂点vに近づけておくためにできる操作の数
first_dfs(0, -1, stones, dists, costs)
# print(stones)
# print(dists)
# print(costs)
second_dfs(0, -1, 0, 0)
print(-1)

import sys
from heapq import nlargest

sys.setrecursionlimit(10000)

def first_dfs(v, p, stones, dists, costs):
    stone = s[v]
    dist = 0
    cost = 0
    children_dists = []
    for u in links[v]:
        if u == p:
            continue
        us, ud, uc = first_dfs(u, v, stones, dists, costs)
        stone += us
        dist += us + ud
        cost += uc
        children_dists.append((us + ud, uc))
    # print(v, p, stone, dist, cost, children_dists)
    if len(children_dists) > 1:
        md, mc = max(children_dists)
        if dist - md < md - mc * 2:
            cost = dist - md + mc
        else:
            cost = dist // 2
        # print(v, p, md, hd, dist, cost)
    stones[v] = stone
    dists[v] = dist
    costs[v] = cost
    return stone, dist, cost

def second_dfs(v, p, pd, pc):
    children_dists = []
    dist = 0

    for u in links[v]:
        if u == p:
            dist += pd
            children_dists.append((pd, pc))
            continue
        ud = stones[u] + dists[u]
        uc = costs[u]
        dist += ud
        children_dists.append((ud, uc))
    # print(v, p, pd, pc, dist, children_dists)

    # only when source and leaf node
    if len(children_dists) == 1:
        u = next(iter(links[v]))
        return second_dfs(u, v, s[v], 0)

    (md1, mc1), (md2, mc2) = nlargest(2, children_dists)
    ret = INF

    hd, m = divmod(dist, 2)
    # print(' ', hd, m, md1, mc1, dist - md1, md1 - mc1 * 2)
    if m == 0 and dist - md1 >= md1 - mc1 * 2:
        ret = min(ret, hd)

    for u in links[v]:
        if u == p:
            continue
        us = stones[u]
        ud = dists[u]
        uc = costs[u]

        # dist=0 node cannot be a center
        if ud == 0:
            continue
        usd = us + ud
        if usd == md1 and uc == mc1:
            md, mc = md2, mc2
        else:
            md, mc = md1, mc1
        td = dist - usd
        if td - md < md - mc * 2:
            vc = td - md + mc
        else:
            vc = td // 2
        result = second_dfs(u, v, td + (all_stones - us), vc)
        ret = min(ret, result)

    return ret

n = int(input())
s = list(map(int, input()))
links = [set() for _ in [0] * n]
for line in sys.stdin:
    a, b = map(int, line.split())
    a -= 1
    b -= 1
    links[a].add(b)
    links[b].add(a)
all_stones = sum(s)
if all_stones == 1:
    print(0)
    exit()
stones = [0] * n  # 1を根とした木の、頂点vの部分木以下（自身含む）にある石の数
dists = [0] * n  # 頂点vの部分木以下にある石 x それぞれのvとの距離 の和
costs = [0] * n  # 頂点v以下の石同士で、最大限頂点vに近づけておくためにできる操作の数
first_dfs(0, -1, stones, dists, costs)
# print(stones)
# print(dists)
# print(costs)
INF = 10**10
ret = second_dfs(0, -1, 0, 0)
print(-1 if ret == INF else ret)


N = int(input())

g = 1000003
for x, d, n in (map(int, input().split()) for _ in range(N)):
    ans = 1

    for _ in range(n):
        ans = ans * x % g
        x += d

    print(ans)

import math

N = int(input())

g = 1000003

fr = [1] * g
for x in range(2, g):
    fr[x] = x * fr[x - 1] % g

def div(a, b):
    return a * pow(b, g - 2, g) % g

for x, d, n in (map(int, input().split()) for _ in range(N)):
    ans = 1

    if d == 0:
        print(pow(x, n, g))

    else:
        s = div(x, d)
        x, y = s + n - 1, s - 1
        if s + n - 1 < g:
            print(div(fr[x], fr[y]) * pow(d, n, g) % g)
        else:
            print(0)


a, p = map(int, input())
print((3 * a + p) // 2)

a, p = map(int, input().split())
print((3 * a + p) // 2)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03029/Python/s938793340.py", line 1, in <module>
    a, p = map(int, input())
ValueError: invalid literal for int() with base 10: ' '


A, P = map(int, input.split(" "))
print((3 * A + P) // 2)

A, P = map(int, input().split(" "))
print((3 * A + P) // 2)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03029/Python/s942506931.py", line 1, in <module>
    A, P = map(int, input.split(" "))
AttributeError: 'builtin_function_or_method' object has no attribute 'split'


n = int(input())
a = []
for i in range(n):
    s, p = list(map(int, input().split()))
    a.append((s, -int(p), i))
a.sort()

for _, _, i in a:
    print(i + 1)

n = int(input())
a = []
for i in range(n):
    s, p = input().split()
    a.append((s, -int(p), i))
a.sort()

for _, _, i in a:
    print(i + 1)

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


n = int(input())
res = list(enumerate(((s[0], int(s[1])) for s in input().split()), 1))

res.sort(key=lambda r: r[1])

[print(r[0]) for r in res]

n = int(input())

res = []
for i in range(n):
    s, s_p = input().split()
    p = int(s_p)
    res.append(((s, -p), i + 1))

res.sort(key=lambda r: r[0])

for r in res:
    print(r[1])

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03030/Python/s639248400.py", line 2, in <module>
    res = list(enumerate(((s[0], int(s[1])) for s in input().split()), 1))
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03030/Python/s639248400.py", line 2, in <genexpr>
    res = list(enumerate(((s[0], int(s[1])) for s in input().split()), 1))
ValueError: invalid literal for int() with base 10: 'h'


#!/usr/bin/env python3
n = int(input())
res = [(i, *input().split()) for i in range(n)]

res.sort(key=lambda x: (x[1], -int(x[2])))

for r in res:
    print(r[0] + 1)

#!/usr/bin/env python3
n = int(input())
res = [[i] + input().split() for i in range(n)]

res.sort(key=lambda x: (x[1], -int(x[2])))

for r in res:
    print(r[0] + 1)


n = int(input())
f = []
s = []
p = []
for i in range(n):
    f += [list(map(str, input().split(" ")))]
    s += [f[i][0]]
    p += [int(f[i][1])]
print(p)
s.sort()
p.sort(reverse=True)
print(p)
ans = [0] * n
count = 0
for i in s:
    for j in p:
        if [i, str(j)] in f:
            ans[count] = f.index([i, str(j)]) + 1
            p[p.index(j)] = 0
            s[s.index(i)] = 0
            count += 1

for i in range(n):
    print(ans[i])

n = int(input())
sr = []
ans = [0] * n
for _ in range(n):
    s, r = input().split()
    sr += [[str(s), int(r)]]
se = sorted(sr, key=lambda x: (x[0], -x[1]))
for i in range(n):
    ans[i] = sr.index(se[i]) + 1
for i in range(n):
    print(ans[i])


N = int(input())
SP = [(i + 1, input().split()) for i in range(N)]
P = [[0, 0, 0] for _ in range(N)]
for i in range(N):
    P[i][0] = SP[i][0]
    P[i][1] = SP[i][1][0]
    P[i][2] = int(SP[i][1][1])
P.sort(key=lambda x: x[1][1], reverse=True)
P.sort(key=lambda x: x[1][0])

for p in P:
    print(p[0])

N = int(input())
SP = [(i + 1, input().split()) for i in range(N)]
P = [[0, 0, 0] for _ in range(N)]
for i in range(N):
    P[i][0] = SP[i][0]
    P[i][1] = SP[i][1][0]
    P[i][2] = int(SP[i][1][1])
P.sort(key=lambda x: x[2], reverse=True)
P.sort(key=lambda x: x[1])

for p in P:
    print(p[0])


swithCount, lightCount = map(int, input().split())
swithList = [0] * lightCount

for i in range(swithCount):
    connectedLightList = list(map(int, input().split()))
    for lightIndex in connectedLightList[1:]:
        lightIndex -= 1
        swithList[i] = swithList[i] | 1 << lightIndex

expectedLightStatusList = list(map(int, input().split()))
expectedLightStatus = 0

for i, eachStatus in enumerate(expectedLightStatusList):
    expectedLightStatus = expectedLightStatus | eachStatus << i

resultCount = 0
for eachSwitchSet in range(1 << swithCount):
    actuallyLightStatus = 0
    for switchIndex in range(swithCount):
        if eachSwitchSet >> switchIndex & 1:
            actuallyLightStatus = actuallyLightStatus ^ swithList[switchIndex]

    if expectedLightStatus == actuallyLightStatus:
        resultCount += 1

print(resultCount)

swithCount, lightCount = map(int, input().split())
swithList = [0] * swithCount

for lightIndex in range(lightCount):
    connectedSwitchList = list(map(int, input().split()))
    for si in connectedSwitchList[1:]:
        switchIndex = si - 1
        swithList[switchIndex] = swithList[switchIndex] | 1 << lightIndex

expectedLightStatusList = list(map(int, input().split()))
expectedLightStatus = 0

for i, eachStatus in enumerate(expectedLightStatusList):
    expectedLightStatus = expectedLightStatus | eachStatus << i

resultCount = 0
for eachSwitchSet in range(1 << swithCount):
    actuallyLightStatus = 0
    for switchIndex in range(swithCount):
        if eachSwitchSet >> switchIndex & 1:
            actuallyLightStatus = actuallyLightStatus ^ swithList[switchIndex]

    if expectedLightStatus == actuallyLightStatus:
        resultCount += 1

print(resultCount)


import itertools

N, M = map(int, input().split())
connected_switches = [[int(x) - 1 for x in input().split()[1:]] for x in range(M)]
conditions = list(map(int, input().split()))

ok = 0
for patterns in itertools.product((0, 1), repeat=M):
    patterns = list(patterns)
    is_lighting = True
    for i, lights in enumerate(connected_switches):
        turned_sw = sum([patterns[x] for x in lights])
        if turned_sw % 2 != conditions[i]:
            is_lighting = False
            break
    if is_lighting:
        ok += 1

print(ok)

import itertools

N, M = map(int, input().split())
connected_switches = [[int(x) - 1 for x in input().split()[1:]] for x in range(M)]
conditions = list(map(int, input().split()))

ok = 0
for patterns in itertools.product((0, 1), repeat=N):
    patterns = list(patterns)
    is_lighting = True
    for i, lights in enumerate(connected_switches):
        turned_sw = sum([patterns[x] for x in lights])
        if turned_sw % 2 != conditions[i]:
            is_lighting = False
            break
    if is_lighting:
        ok += 1

print(ok)


n, k = map(int, input().split())
v = [int(i) for i in input().split()]
ans = 0
for a in range(k + 1):
    pa, va = v[:a], v[a:]
    for b in range(k - a + 1):
        pb = pa + va[-b:] if b > 0 else pa
        pb.sort()
        s = sum(pb)
        for c in range(min(k - a - b, a + b)):
            s -= pb[c]
            ans = max(ans, s)
print(ans)

n, k = map(int, input().split())
v = [int(i) for i in input().split()]
ans = 0
for a in range(min(n, k) + 1):
    pa, va = v[:a], v[a:]
    for b in range(min(n, k) - a + 1):
        pb = pa + va[-b:] if b > 0 else pa
        pb.sort()
        s = sum(pb)
        ans = max(s, ans)
        for c in range(min(k - a - b, a + b)):
            s -= pb[c]
            ans = max(s, ans)
print(ans)


N, K = map(int, input().split())
d = list(map(int, input().split()))
left = [0]
left_m = []
right = [0]
right_m = []
for i, l, r in zip(range(K), d, d[::-1]):
    left.append(left[i] + l)
    left_m.append(l if l < 0 else 0)
    right.append(right[i] + r)
    right_m.append(r if r < 0 else 0)
point = 0
for i in range(K):
    for j in range(K - i):
        p = K - i - j
        minus = list(sorted(left_m[:i] + right_m[:j]))
        point = max(point, left[i] + right[j] - sum(minus[:p]))
print(point)

N, K = map(int, input().split())
d = list(map(int, input().split()))
left = [0]
left_m = []
right = [0]
right_m = []
for i, l, r in zip(range(K), d, d[::-1]):
    left.append(left[i] + l)
    left_m.append(l if l < 0 else 0)
    right.append(right[i] + r)
    right_m.append(r if r < 0 else 0)
point = 0
m = min(N, K)
for i in range(m + 1):
    for j in range(m - i + 1):
        p = K - i - j
        minus = list(sorted(left_m[:i] + right_m[:j]))
        point = max(point, left[i] + right[j] - sum(minus[:p]))
print(point)


N, K = map(int, input().split())
V = list(map(int, input().split()))
que = []
ma = 0
for i in range(K):
    P = K - i
    for p in range(P + 1):
        q1 = []
        q2 = []
        s = 0
        for j in range(p):
            if V[j] >= 0:
                s += V[j]
            else:
                q1.append(V[j])
        if len(q1) == p:
            q1 = []
        for j in range(N - 1, N - (P - p) - 1, -1):
            if V[j] >= 0:
                s += V[j]
            else:
                q2.append(V[j])
        if len(q2) == P - p:
            q2 = []

        q = sorted(q1 + q2)
        if len(q) < i:
            t = 0
        else:
            t = sum(q[i:])
        ma = max(s + t, ma)

print(ma)

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

ma = 0
for i in range(K):
    P = K - i
    for p in range(P + 1):
        q1 = []
        q2 = []
        s = 0
        for j in range(min(N, p)):
            if V[j] >= 0:
                s += V[j]
            else:
                q1.append(V[j])
        if len(q1) == p:
            q1 = []
        for j in range(N - 1, max(p - 1, N - (P - p) - 1), -1):
            if V[j] >= 0:
                s += V[j]
            else:
                q2.append(V[j])
        if len(q2) == P - p:
            q2 = []

        q = sorted(q1 + q2)
        if len(q) < i:
            t = 0
        else:
            t = sum(q[i:])
        ma = max(s + t, ma)

print(ma)


from operator import itemgetter
import sys

input = sys.stdin.readline

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

events = []

for _ in range(N):
    s, t, x = map(int, input().split())
    add_event = (s - x, 1, x)
    remove_event = (t - x, -1, x)
    events.append(add_event)
    events.append(remove_event)

events.sort(key=itemgetter(0))  # イベント処理時刻昇順ソート

under_construction = set()

cur = 0
for _ in range(Q):
    d = int(input())
    # print('d', d)
    while cur < N * 2 and events[cur][0] <= d:
        exec_time, event_type, under_construction_x = events[cur]
        # print(cur, exec_time, event_type, under_construction_x)
        if event_type == 1:
            # add_event
            under_construction.add(under_construction_x)
        else:
            # remove_event
            under_construction.discard(under_construction_x)
        cur += 1
    # print('cur', cur, 'events', events)
    # print('uc', under_construction)
    print(min(under_construction) if under_construction else -1)

    # print()

from operator import itemgetter
import sys

input = sys.stdin.readline

inf = float("inf")

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

events = []

for _ in range(N):
    s, t, x = map(int, input().split())
    add_event = (s - x, 1, x)
    remove_event = (t - x, -1, x)
    events.append(add_event)
    events.append(remove_event)

events.sort(key=itemgetter(0))  # イベント処理時刻昇順ソート

under_construction = set()

min_stop = inf
chg_flg = False

cur = 0
for _ in range(Q):
    d = int(input())
    while cur < N * 2 and events[cur][0] <= d:
        exec_time, event_type, under_construction_x = events[cur]
        if event_type == 1:  # add_event
            under_construction.add(under_construction_x)
            if not chg_flg:
                min_stop = min(min_stop, under_construction_x)
        else:  # remove_event
            under_construction.discard(under_construction_x)
            if not chg_flg and min_stop == under_construction_x:
                chg_flg = True
        cur += 1

    if chg_flg:
        min_stop = min(under_construction) if under_construction else inf
        chg_flg = False
    print(min_stop if min_stop != inf else -1)


import numpy as np

def score(cache, sss, a, ab, d):
    mat = cache[ab]
    if mat is None:
        mat = cache[ab] = np.cumsum(np.resize(sss, ((n - 1) // ab + 1, ab)).T, axis=1)
    mat_a = mat[a % ab]
    return mat[0][d] + mat_a[-1] - mat_a[-d - 2]

n = int(input())
sss = list(map(int, input().split()))
sss.extend([0] * n)
sss = np.array(sss, dtype=np.int64)

ans = 0
cache = [None] * n
for ab in range(1, int((n - 2) ** 0.5) + 1):
    for remain in range(ab, n - 3, ab):
        a = n - remain - 1
        d = remain // ab
        if remain < a:
            ans = max(ans, score(cache, sss, a, ab, d))
            if ab != d:
                ans = max(ans, score(cache, sss, a, d, ab))
        else:
            if a % ab > 0:
                ans = max(ans, score(cache, sss, a, ab, d))
            if a > d and ab != d and a % d > 0:
                ans = max(ans, score(cache, sss, a, d, ab))
print(ans)

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

ans = 0
for c in range(1, n // 2):
    a = n - 1 - c
    k = c
    tmp = 0
    while a > c and a != k and a + c != k:
        tmp += sss[a] + sss[k]
        ans = max(ans, tmp)
        a -= c
        k += c
print(ans)


A, B = map(int, input())

if A >= 13:
    print(B)
elif A >= 6:
    print(B // 2)
else:
    print(0)

A, B = map(int, input().split())

if A >= 13:
    print(B)
elif A >= 6:
    print(B // 2)
else:
    print(0)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03035/Python/s602871516.py", line 1, in <module>
    A, B = map(int, input())
ValueError: invalid literal for int() with base 10: ' '


import itertools
from collections import Counter

def main():
    N, M = map(int, input().split())
    LR = []
    for _ in range(M):
        L, R = map(int, input().split())
        LR.append(list(range(L, R + 1)))
    LR = list(itertools.chain.from_iterable(LR))
    C = Counter(LR)

    ans = 0
    for c in C.values():
        if c == M:
            ans += 1
    print(ans)

if __name__ == "__main__":
    main()

def main():
    N, M = map(int, input().split())
    L = 0
    R = N
    for _ in range(M):
        l, r = map(int, input().split())
        if L < l:
            L = l
        if R > r:
            R = r
    ans = 0
    if L <= R:
        ans = R - L + 1
    print(ans)

if __name__ == "__main__":
    main()


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

ans = set(list(range(1, N + 1)))
for lr in LR:
    l, r = lr
    ans = ans & set(list(range(l, r + 1)))
print(len(list(ans)))

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

A, B = 1, N
for lr in LR:
    L, R = lr
    if R < A or B < L:
        print(0)
        exit()

    if A <= L <= R <= B:
        A, B = L, R
    elif L <= A <= R <= B:
        B = R
    elif A <= L <= B <= R:
        A = L
print(B - A + 1)


# C - Prison

N, M = map(int, input().split())
ls = [i for i in range(1, N + 1)]
for _ in range(M):
    l, r = map(int, input().split())
    ls = set(ls) & set([i for i in range(l, r + 1)])

print(len(ls))

# C - Prison

N, M = map(int, input().split())
left = 0
right = 10**5
for _ in range(M):
    l, r = map(int, input().split())
    left, right = max(left, l), min(right, r)

print(len([i for i in range(left, right + 1)]) if left <= right else 0)


from sys import stdin, setrecursionlimit

def main():
    input = stdin.buffer.readline
    n, m = map(int, input().split())
    counts = [0] * n
    for _ in range(m):
        l, r = map(int, input().split())
        for i in range(l - 1, r):
            counts[i] += 1
    print(counts.count(m))

if __name__ == "__main__":
    setrecursionlimit(10000)
    main()

from sys import stdin, setrecursionlimit

def main():
    input = stdin.buffer.readline
    n, m = map(int, input().split())
    l_max = 0
    r_min = float("inf")
    for _ in range(m):
        l, r = map(int, input().split())
        l_max = max(l_max, l)
        r_min = min(r_min, r)
    print(max(r_min + 1 - l_max, 0))

if __name__ == "__main__":
    setrecursionlimit(10000)
    main()


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

Ls = [0] * M
Rs = [0] * M

for i in range(M):
    Ls[i], Rs[i] = list(map(int, input().split()))

count = 0
for i in range(N):
    judge = True
    for k in range(M):
        L = Ls[k]
        R = Rs[k]
        if not (L <= i + 1 <= R):
            judge = False
    if judge:
        count += 1
print(count)

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

maxvL = 0
minvR = 1000000
for i in range(M):
    L, R = list(map(int, input().split()))
    if maxvL < L:
        maxvL = L
    if minvR > R:
        minvR = R

count = 0
for i in range(N):
    if maxvL <= i + 1 <= minvR:
        count += 1
print(count)


n, m = map(int, input().split())

li_w = list()

for _ in range(m):
    li_w.append(tuple(map(int, input().split())))

answer = set()

for idx, w in enumerate(li_w):
    if idx == 0:
        answer = set(range(w[0], w[1] + 1))
    else:
        answer = answer.intersection(range(w[0], w[1] + 1))

print(len(answer))

n, m = map(int, input().split())

li_w = list()

for _ in range(m):
    li_w.append(tuple(map(int, input().split())))

w_l = 0
w_r = 999999

for w in li_w:
    w_l = max(w_l, w[0])
    w_r = min(w_r, w[1])

if w_r >= w_l:
    print(w_r - w_l + 1)
else:
    print(0)


def main():
    N, M = map(int, input().split())
    A = [0] * N
    for _ in range(M):
        L, R = map(int, input().split())
        for i in range(L - 1, R):
            A[i] += 1
    print(A.count(M))

main()

def main():
    N, M = map(int, input().split())
    A = [0] * (N + 1)
    for _ in range(M):
        L, R = map(int, input().split())
        A[L - 1] += 1
        A[R] -= 1
    c = 0
    ans = 0
    for i, a in enumerate(A):
        c += a
        if c == M:
            ans += 1
    print(ans)

main()


n, m = map(int, input().split())
Authority = [list(map(int, input().split())) for _ in range(m)]
cards = set(range(1, n + 1))

for i in range(m):
    gate = set(range(Authority[i][0], Authority[i][1] + 1))
    cards &= gate
print(len(cards))

n, m = map(int, input().split())
Authority = [list(map(int, input().split())) for _ in range(m)]
cards = list(range(1, n + 2))
l_list = []
r_list = []
for i in range(m):
    l_list.append(Authority[i][0])
    r_list.append(Authority[i][1])

print(len(cards[max(l_list) : min(r_list) + 1]))


from sys import exit

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

ans = []

for i in range(M):
    L, R = map(int, input().split())

    if i == 0:
        for card in range(L, R + 1):
            ans.append(card)
        continue

    if ans[0] < L:
        for card in range(ans[0], L):
            ans.remove(card)

    if R < ans[-1]:
        for card in range(R + 1, ans[-1] + 1):
            ans.remove(card)

    if not ans:
        print(0)
        exit()

print(len(ans))

from sys import exit

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

L = []
R = []

for i in range(M):
    l, r = map(int, input().split())
    L.append(l)
    R.append(r)

l_max = max(L)
r_min = min(R)

if (r_min - l_max) < 0:
    print(0)
else:
    print(r_min - l_max + 1)


(n, m) = map(int, input().split())
counts = [0 for _ in range(n)]
for _ in range(m):
    gate_i = list(map(int, input().split()))
    for i in range(gate_i[0] - 1, gate_i[1]):
        counts[i] += 1
counts.sort()
ans = 0
for count in counts:
    ans += 1 if m == count else 0
print(ans)

(n, m) = map(int, input().split())

def intersect(lhs, rhs):
    if lhs[1] < rhs[0] or rhs[1] < lhs[0]:
        return [0, 0]
    min_value = lhs[0] if lhs[0] > rhs[0] else rhs[0]
    max_value = lhs[1] if lhs[1] < rhs[1] else rhs[1]
    return [min_value, max_value]

ans = [-1, 2 * 10**5]
for _ in range(m):
    ans = intersect(ans, list(map(int, input().split())))
    if 0 == ans[0] and 0 == ans[1]:
        print(0)
        exit(0)
print(ans[1] - ans[0] + 1)


def main():
    n, m = map(int, input().split())
    lr_lst = [list(map(int, input().split())) for _ in range(m)]

    ans = 0

    for i in range(1, n + 1):
        is_able = True
        for j in range(m):
            if not lr_lst[j][0] <= i <= lr_lst[j][1]:
                is_able = False
                break
        if is_able:
            ans += 1

    print(ans)

if __name__ == "__main__":
    main()

def main():
    n, m = map(int, input().split())
    lr_lst = [list(map(int, input().split())) for _ in range(m)]
    left = 0
    right = n + 1

    for i in range(m):
        if left < lr_lst[i][0]:
            left = lr_lst[i][0]
        if lr_lst[i][1] < right:
            right = lr_lst[i][1]

    if right - left < 0:
        print(0)
    else:
        print(right - left + 1)

if __name__ == "__main__":
    main()


N, M = map(int, input().split())
L = [0] * M
R = [0] * M
count = 0
for i in range(M):
    L[i], R[i] = map(int, input().split())
for i in range(N):
    clear = 0
    for j in range(M):
        if L[j] <= i + 1 <= R[j]:
            clear += 1
        else:
            break
    if clear == M:
        count += 1
print(count)

N, M = map(int, input().split())
L = [0] * M
R = [0] * M
count = 0
for i in range(M):
    L[i], R[i] = map(int, input().split())
Lmax = max(L)
Rmin = min(R)
if Lmax <= Rmin:
    print(Rmin - Lmax + 1)
else:
    print(0)


import sys

input = sys.stdin.readline

n, m = map(int, input().split())

l_first, r_first = map(int, input().split())

answer_set = {value for value in range(l_first, r_first + 1)}

for _ in range(m - 1):
    l_current, r_current = map(int, input().split())
    current_set = {value for value in range(l_current, r_current + 1)}
    answer_set.intersection_update(current_set)

print(len(answer_set))

import sys

input = sys.stdin.readline

n, m = map(int, input().split())

l_list = []
r_list = []

for _ in range(m):
    l, r = map(int, input().split())
    l_list.append(l)
    r_list.append(r)

l_maybe_answer = max(l_list)
r_maybe_answer = min(r_list)

if l_maybe_answer <= r_maybe_answer:
    print(min(r_list) - max(l_list) + 1)
else:
    print(0)


n, m = map(int, input().split())
ans = set(range(1, n + 1))
for _ in range(m):
    l, r = map(int, input().split())
    st = set(range(l, r + 1))
    ans &= st
print(len(ans))

def solve2():
    n, m = map(int, input().split())
    L = 1
    R = n
    for _ in range(m):
        l, r = map(int, input().split())
        L = max(L, l)
        R = min(R, r)
    if L <= R:
        print(R - L + 1)
    else:
        print(0)

solve2()


n, m = map(int, input().split())
a = [list(map(int, input().split())) for i in range(m)]

if len(a) == 1:
    print(a[0][1] - a[0][0] + 1)
else:
    ans = n
    for i in range(1, n + 1):
        for j in range(m):
            if a[j][0] <= i <= a[j][1]:
                continue
            else:
                ans -= 1
                break
    print(ans)

n, m = map(int, input().split())

left = []
right = []
for i in range(m):
    a, b = map(int, input().split())
    left.append(a)
    right.append(b)

if min(right) >= max(left):
    print(min(right) - max(left) + 1)
else:
    print(0)


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

ans = [table[0], table[1]]

for i in table:
    if ans[0] >= i[0] <= ans[1]:
        ans[0] = i[0]
    if ans[0] >= i[1] <= ans[1]:
        ans[1] = i[1]

print(ans[1] - ans[0] + 1)

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

ans = [table[0][0], table[0][1]]
cnt = 0

for i in table[1:]:
    if ans[0] <= i[0] <= ans[1]:
        ans[0] = i[0]
    if ans[0] <= i[1] <= ans[1]:
        ans[1] = i[1]
    if ans[1] < i[0] or i[1] < ans[0]:
        cnt += 1
        break

if cnt != 0:
    print(0)
else:
    print(ans[1] - ans[0] + 1)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03037/Python/s777390978.py", line 7, in <module>
    if ans[0] >= i[0] <= ans[1]:
TypeError: '>=' not supported between instances of 'list' and 'int'


#!/usr/bin/env python3
import sys

N, M = map(int, input().rstrip().split())

L = []
R = []
for _ in range(M):
    l, r = map(int, input().rstrip().split())
    L.append(l)
    R.append(r)

Ans = set(range(L[0], R[0] + 1))
for i in range(1, len(L)):
    Ans = set(range(L[i], R[i] + 1)) & Ans
    if not Ans:
        print(0)
        sys.exit(0)

print(len(Ans))

#!/usr/bin/env python3
import sys

N, M = map(int, input().rstrip().split())

L = []
R = []
for _ in range(M):
    l, r = map(int, input().rstrip().split())
    L.append(l)
    R.append(r)

Ans = min(R) - max(L) + 1
if Ans < 0:
    Ans = 0
print(Ans)


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

id_list = [0] * N

for _ in range(M):
    L, R = map(int, input().split())
    for i in range(L, R + 1):
        id_list[i - 1] += 1

print(sorted(id_list, reverse=True).count(M))

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

L, R = 1, N
for _ in range(M):
    Li, Ri = map(int, input().split())
    if L <= Li:
        L = Li
    if Ri <= R:
        R = Ri

print(R - L + 1 if (R >= L) else 0)


n, m = map(int, input().split())
lr = [list(map(int, input().split())) for _ in range(m)]
ans = []
for i in range(m):
    res = []
    for j in range(lr[i][0], lr[i][1] + 1):
        res.append(j)
    if i == 0:
        ans = set(res)
    else:
        ans = set(ans) & set(res)
print(len(ans))

n, m = map(int, input().split())
mi, ma = 1, n
for _ in range(m):
    l, r = map(int, input().split())
    mi = max(l, mi)
    ma = min(r, ma)
print(max(0, ma - mi + 1))


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

c = [0 for _ in range(N)]
cnt = 0
for i, (l, r) in enumerate(LR):
    for j in range(l - 1, r):
        c[j] += i + 1
    cnt += i + 1

s = [1 if k == cnt else 0 for k in c]

print(sum(s))

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

left = 1
right = N

for l, r in LR:
    left = max(left, l)
    right = min(right, r)

ans = right - left

print(ans + 1 if ans >= 0 else 0)


N, M = map(int, input().split())
A = []
for i in range(M):
    L, R = map(int, input().split())
    if i == 0:
        S = set(list(range(L, R + 1)))
    else:
        S = S & set(list(range(L, R + 1)))
        if len(S) == 0:
            break

# L = set(A[0])
# for i in range(1, M):
#     L = L & set(A[i])

print(len(S))

N, M = map(int, input().split())
A = []
for i in range(M):
    L, R = map(int, input().split())
    if i == 0:
        Lmax = L
        Rmin = R
    else:
        Lmax = max(L, Lmax)
        Rmin = min(R, Rmin)

# L = set(A[0])
# for i in range(1, M):
#     L = L & set(A[i])

if Rmin - Lmax < 0:
    print(0)
else:
    print(Rmin - Lmax + 1)


N, M = map(int, input().split())
A = list(map(int, input().split()))
BC = [list(map(int, input().split())) for i in range(M)]
BC = sorted(BC, key=lambda x: x[1])
A.sort()
i = 0
for b, c in BC[::-1]:
    if i == N:
        break
    for _ in range(b):
        if c > A[i]:
            A[i] = c
            i += 1
        else:
            break

print(sum(A))

N, M = map(int, input().split())
A = list(map(int, input().split()))
BC = [list(map(int, input().split())) for i in range(M)]
BC = sorted(BC, key=lambda x: x[1])
A.sort()
i = 0
for b, c in BC[::-1]:
    for _ in range(b):
        if i == N:
            break
        if c > A[i]:
            A[i] = c
            i += 1
        else:
            break

print(sum(A))


import heapq

n, m = map(int, input().split())
a = list(map(int, input().split()))
heapq.heapify(a)
for _ in range(m):
    b, c = map(int, input().split())
    for _ in range(b):
        tmp = heapq.heappop(a)
        if tmp >= c:
            heapq.heappush(a, tmp)
            break
        else:
            heapq.heappush(a, c)
print(sum(a))

n, m = map(int, input().split())
A = list(map(int, input().split()))
d = {}
for a in A:
    d[a] = 1 if a not in d else d[a] + 1
for _ in range(m):
    b, c = map(int, input().split())
    d[c] = b if c not in d else d[c] + b
ans = 0
cnt = 0
L = sorted(d, reverse=True)
for k in L:
    if d[k] + cnt < n:
        ans += k * d[k]
        cnt += d[k]
    else:
        ans += k * (n - cnt)
        break
print(ans)


import sys

input = sys.stdin.readline

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

cards = sorted(A)
op.sort(key=lambda x: -x[1])

i = 0

for m in range(M):
    b, c = op[m]
    for _ in range(b):
        if cards[i] < c:
            cards[i] = c
            i += 1
        if i >= N:
            break
    else:
        continue
    break

print(sum(cards))

import sys

input = sys.stdin.readline

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

cards = sorted(A)
op.sort(key=lambda x: -x[1])

i = 0

for m in range(M):
    b, c = op[m]
    for _ in range(b):
        if cards[i] < c:
            cards[i] = c
            i += 1
            if i >= N:
                break
        else:
            break
    else:
        continue
    break

print(sum(cards))


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

# n番目の要素でソートsort
BC = sorted(BC, reverse=True, key=lambda x: x[1])

m = A[0]
D = []
p = 0
for b, c in BC:
    if c > m:
        _ = [D.append(c) for i in range(b)]
        p += 1
        if p > N:
            break
    else:
        continue

D.append(0)

for i, d in enumerate(D):
    if i > N:
        break
    if A[i] < d:
        A[i] = d
    else:
        break

print(sum(A))

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

# n番目の要素でソートsort
BC = sorted(BC, reverse=True, key=lambda x: x[1])

m = A[0]
D = []
for b, c in BC:
    if c > m:
        _ = [D.append(c) for i in range(b)]
    else:
        continue
    if len(D) > N:
        break

D.append(0)

for i, d in enumerate(D):
    if i >= N:
        break
    if A[i] < d:
        A[i] = d
    else:
        break

print(sum(A))


#!/usr/bin/env python3
import bisect
import numpy as np

N, M = list(map(int, input().split()))
a_list = list(map(int, input().split()))
bc_list = []

for _ in range(M):
    b, c = list(map(int, input().split()))
    bc_list.append((b, c))

bc_list = sorted(bc_list, key=lambda x: x[1], reverse=True)
now_list = np.array(sorted(a_list))
fix_list = np.array([])
min_a = min(a_list)

for bc in bc_list:
    b, c = bc
    if min_a >= c:
        # もう置き換えても合計値は増えない
        break
    # cより小さい数は何個あるか？
    # 線形探索だとTLEになるので、2分探索で考える
    c_index = bisect.bisect_right(now_list, c)
    target_index = c_index if c_index < b else b

    # c_indexまでをcで置き換えても、順序の入れ替えはない
    now_list[:target_index] = c
    # c_index以前の整数は使用確定なので掃き出す
    fix_list = np.hstack([fix_list, now_list[:target_index]])
    now_list = now_list[target_index:]
    min_a = now_list[0]

fix_list = np.hstack([fix_list, now_list])
ans = fix_list.sum()
ans = int(ans)
print(ans)

#!/usr/bin/env python3
import bisect
import numpy as np

N, M = list(map(int, input().split()))
a_list = list(map(int, input().split()))
bc_list = []

for i in range(M):
    try:
        b, c = list(map(int, input().split()))
        bc_list.append((b, c))
    except:
        M = i

bc_list = sorted(bc_list, key=lambda x: x[1], reverse=True)
a_list = sorted(a_list)

fix_list = []
s = 0
b, c = bc_list[0]
bc_index = 0
now_b, now_c = 0, c

for i, a in enumerate(a_list):
    # a = a_list[i]
    if now_b >= b:
        bc_index += 1
        if bc_index >= len(bc_list):
            # TODO: 残りを足す
            fix_list.append(a)
            s += a
            continue
        now_b = 0
        b, c = bc_list[bc_index]

    if a < c:
        fix_list.append(c)
        s += c
    else:
        fix_list.append(a)
        s += a
    now_b += 1

ans = s
print(ans)


n, m = map(int, input().split())
a = list(map(int, input().split()))
bc = [0] * m
ans = []
a.sort()
for i in range(m):
    bc[i] = list(map(int, input().split()))
bc.sort(key=lambda x: x[1], reverse=True)

j = 0
for i in range(n):
    if bc[j][0] == 0:
        j += 1
    if j >= m:
        ans.append(a[i])
    elif a[i] >= bc[j][1]:
        ans.append(a[i])
    else:
        ans.append(bc[j][1])
        bc[j][0] -= 1

print(sum(ans))

n, m = map(int, input().split())
a = list(map(int, input().split()))
bc = [0] * m
ans = []
a.sort()
for i in range(m):
    bc[i] = list(map(int, input().split()))
bc.sort(key=lambda x: x[1], reverse=True)

j = 0
for i in range(n):
    if j < m:
        if bc[j][0] == 0:
            j += 1
    if j >= m:
        ans.append(a[i])
    elif a[i] >= bc[j][1]:
        ans.append(a[i])
    else:
        ans.append(bc[j][1])
        bc[j][0] -= 1

print(sum(ans))


N, M = map(int, input().split())
A = list(map(int, input().split()))
operation = []
ans = 0

for _ in range(M):
    t = tuple(map(int, input().split()))
    operation.append(t)

operation.sort(key=lambda x: x[1], reverse=True)
A.sort()

while A and operation:
    if A[-1] >= operation[0][1]:
        ans += A[-1]
        A.pop(-1)
    else:
        cnt = 0
        for i in range(operation[0][0]):
            if len(A) == i or A[i] > operation[0][1]:
                cnt = i
                break
        else:
            cnt = operation[0][0]
        for _ in range(cnt):
            A.pop(0)
        ans += cnt * operation[0][1]
        operation.pop(0)

ans += sum(A)

print(ans)

from collections import deque

N, M = map(int, input().split())
A = list(map(int, input().split()))
operation = []
ans = 0

for _ in range(M):
    t = tuple(map(int, input().split()))
    operation.append(t)

operation.sort(key=lambda x: x[1], reverse=True)
A.sort()
A = deque(A)
operation = deque(operation)

while A and operation:
    if A[-1] >= operation[0][1]:
        ans += A[-1]
        A.pop()
    else:
        cnt = 0
        for i in range(operation[0][0]):
            if len(A) == i or A[i] > operation[0][1]:
                cnt = i
                break
        else:
            cnt = operation[0][0]
        for _ in range(cnt):
            A.popleft()
        ans += cnt * operation[0][1]
        operation.popleft()

ans += sum(A)

print(ans)


#!/usr/bin/env python3
N, M = map(int, input().rstrip().split())
A = list(map(int, input().rstrip().split()))

B = []
C = []
for _ in range(M):
    b, c = map(int, input().rstrip().split())
    B.append(b)
    C.append(c)

Index = sorted(range(M), key=lambda i: C[i], reverse=True)

sum = 0
A.sort()
for index in Index:
    if A[0] >= C[index]:
        break
    count = 0
    i = 0
    while True:
        if i >= len(A):
            break
        if A[i] < C[index] and count < B[index]:
            sum += C[index]
            A.pop(i)
            # print(A)
            count += 1
            continue
        if A[i] >= C[index] or count >= B[index]:
            break
        i += 1

if A:
    for a in A:
        sum += a

print(sum)

#!/usr/bin/env python3
N, M = map(int, input().rstrip().split())
A = list(map(int, input().rstrip().split()))

B = []
C = []
for _ in range(M):
    b, c = map(int, input().rstrip().split())
    B.append(b)
    C.append(c)

Index = sorted(range(M), key=lambda i: C[i], reverse=True)

sum = 0
A.sort()
for index in Index:
    if A and A[0] >= C[index]:
        break
    count = 0
    i = 0
    while True:
        if i >= len(A):
            break
        if A[i] < C[index] and count < B[index]:
            sum += C[index]
            A.pop(i)
            # print(A)
            count += 1
            continue
        if A[i] >= C[index] or count >= B[index]:
            break
        i += 1

if A:
    for a in A:
        sum += a

print(sum)


N, M = map(int, input().split())
A = list(map(int, input().split()))
CB = []
for _ in range(M):
    b, c = map(int, input().split())
    CB.append((c, b))

# ascend
A.sort()

# descend
CB.sort(reverse=True)

# fill convert ary
conv = []
for cb in CB:
    c, b = cb
    conv.extend([c] * b)

cl = len(conv)

sum = 0
for i in range(N):
    if i >= cl:
        sum += A[i]
    else:
        sum += max(A[i], conv[i])

print(sum)

N, M = map(int, input().split())
A = list(map(int, input().split()))
CB = []
for _ in range(M):
    b, c = map(int, input().split())
    CB.append((c, b))

# ascend
A.sort()

# descend
CB.sort(reverse=True)

# fill convert ary
conv = []
for cb in CB:
    c, b = cb
    conv.extend([c] * b)
    if len(conv) >= N:
        break

cl = len(conv)

sum = 0
for i in range(N):
    if i >= cl:
        sum += A[i]
    else:
        sum += max(A[i], conv[i])

print(sum)


import bisect

n, m = map(int, input().split())
A = list(map(int, input().split()))
A.sort()

for _ in range(m):
    b, c = map(int, input().split())
    i = bisect.bisect_left(A, c)
    if i >= b:
        A[:b] = [c] * b
    else:
        A[:i] = [c] * i
    A.sort()

answer = sum(A)
print(answer)

from heapq import *

n, m = map(int, input().split())
PAIRS = [[-a, -1] for a in map(int, input().split())]
heapify(PAIRS)

for _ in range(m):
    b, c = map(int, input().split())
    heappush(PAIRS, [-c, -b])

answer = 0
for _ in range(n):
    pair = heappop(PAIRS)
    answer += -pair[0]
    pair[1] += 1
    if pair[1] != 0:
        heappush(PAIRS, pair)

print(answer)


from bisect import bisect_right

n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
a.sort()
bc = [list(map(int, input().split())) for _ in range(m)]
bc.sort(key=lambda x: x[1], reverse=True)

res = 0
for b, c in bc:
    count = bisect_right(a, c, hi=min(b, len(a)))
    res += count * c
    if count > 0:
        a = a[count:]

print(res + sum(a))

from bisect import bisect_right

n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
a.sort()
bc = [list(map(int, input().split())) for _ in range(m)]
bc.sort(key=lambda x: x[1], reverse=True)

res = 0
fin = 0
for b, c in bc:
    count = bisect_right(a, c, lo=fin, hi=min(fin + b, len(a))) - fin
    fin += count
    res += count * c
for i in range(fin, len(a)):
    res += a[i]

print(res)


from heapq import heapify, heappush, heappop

N, M = map(int, input().split())
lst_A = list(map(int, input().split()))

numbers = []
heapify(numbers)
for a in lst_A:
    heappush(numbers, -a)
for _ in range(M):
    b, c = map(int, input().split())
    for _ in range(b):
        heappush(numbers, -c)

ans = -sum(heappop(numbers) for _ in range(N))
print(ans)

from heapq import heapify, heappush, heappop

N, M = map(int, input().split())
lst_A = list(map(int, input().split()))

hq = []
heapify(hq)
for a in lst_A:
    heappush(hq, [-a, 1])
for _ in range(M):
    b, c = map(int, input().split())
    heappush(hq, [-c, b])

ans = 0
while N > 0:
    c, b = heappop(hq)
    c *= -1
    if b < N:
        ans += c * b
        N -= b
    else:
        ans += c * N
        N = 0

print(ans)


N, M = map(int, input().split())
A = sorted(list(map(int, input().split())))
BC = [None] * M
for i in range(M):
    BC[i] = tuple(map(int, input().split()))
BC.sort(key=lambda tpl: tpl[1], reverse=True)  # sort by C descendant

D = [0] * N
i = 0
j = 0
while i < N and j < M:
    b, c = BC[j]
    for k in range(i, i + b):
        D[k] = c
    i += b
    j += 1

for i in range(N):
    A[i] = max(A[i], D[i])

print(sum(A))

N, M = map(int, input().split())
A = sorted(list(map(int, input().split())))
BC = [None] * M
for i in range(M):
    BC[i] = tuple(map(int, input().split()))
BC.sort(key=lambda tpl: tpl[1], reverse=True)  # sort by C descendant

D = [0] * N
i = 0
j = 0
while i < N and j < M:
    b, c = BC[j]
    for k in range(i, min(i + b, N)):
        D[k] = c
    i += b
    j += 1

for i in range(N):
    A[i] = max(A[i], D[i])

print(sum(A))


N, M = map(int, input().split())
A = list(map(int, input().split()))
min_a = min(A)
for i in range(M):
    B, C = map(int, input().split())
    if min_a < C:
        C = [C for i in range(B)]
        A.extend(C)
A = sorted(A, reverse=True)
print(sum(A[:N]))

from collections import Counter

N, M = map(int, input().split())
A = list(map(int, input().split()))
count_a = Counter(A)
A = [(v, k) for k, v in count_a.items()]
for i in range(M):
    B, C = map(int, input().split())
    A.append((B, C))
A = sorted(A, reverse=True, key=lambda x: x[1])
ans = 0
for k, v in A:
    N = N - k
    if N <= 0:
        ans += k * v + N * v
        break
    ans += k * v
print(ans)


import numpy as np
from sys import stdin

n, m = map(int, stdin.readline().split())
a = [int(num) for num in stdin.readline().split()]

cnt_dict = {}
mtr = [stdin.readline().rstrip().split() for _ in range(m)]
for row in mtr:
    cnt_dict.setdefault(int(row[1]), 0)
    cnt_dict[int(row[1])] += int(row[0])
for a_ in a:
    cnt_dict.setdefault(a_, 0)
    cnt_dict[a_] += 1

cnt_dict = sorted(cnt_dict.items(), key=lambda x: -x[0])

cnt = 0
ans = 0

for (k, v) in cnt_dict:
    v_ = np.min([v, n - cnt])
    ans += v_ * k
    cnt += v_
    if cnt == n:
        break

print(ans)

from sys import stdin

n, m = map(int, stdin.readline().split())
a = [int(num) for num in stdin.readline().split()]

cnt_list = [(a[i], 1) for i in range(n)]
for i in range(m):
    b, c = map(int, stdin.readline().split())
    cnt_list.append((c, b))

cnt_list.sort()
cnt_list.reverse()

cnt = n
ans = 0

for (k, v) in cnt_list:
    acc_v = min(v, cnt)
    ans += k * acc_v
    cnt -= acc_v

print(ans)


N, M = [int(i) for i in input().strip().split()]
A = [int(i) for i in input().strip().split()]
A.sort()
for i in range(M):
    B, C = [int(i) for i in input().strip().split()]
    is_changed = False
    for j in range(0, B):
        if A[j] < C:
            A[j] = C
            is_changed = True
        else:
            break
    if is_changed:
        A.sort()
print(sum(A))

N, M = [int(i) for i in input().strip().split()]
A = [int(i) for i in input().strip().split()]
A.sort()

BC = [[0, 0] for _ in range(M)]
for j in range(M):
    BC[j][0], BC[j][1] = [int(i) for i in input().strip().split()]
BC.sort(key=lambda x: x[1])

res = 0
cnt = 0
i = N - 1
j = M - 1
while True:
    if cnt == N:
        break

    if j == -1:
        res += A[i]
        i -= 1
    elif A[i] > BC[j][1]:
        res += A[i]
        i -= 1
    elif A[i] <= BC[j][1]:
        res += BC[j][1]
        BC[j][0] -= 1
        if BC[j][0] == 0:
            j -= 1
    else:
        raise ValueError
    cnt += 1
print(res)


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

D = [C for B, C in opes for _ in range(B)]
D = sorted(D, reverse=True)[:N]

A.sort()
for i, d in enumerate(D):
    if A[i] >= d:
        break
    A[i] = d

print(sum(A))

N, M = map(int, input().split())
A = list(map(int, input().split()))
opes = [tuple(map(int, input().split())) for _ in range(M)]
opes.sort(key=lambda x: -x[1])

D = []
lenD = 0
for B, C in opes:
    D += [C] * B
    lenD += B
    if lenD >= N:
        break

A.sort()
for i, d in enumerate(D[:N]):
    if A[i] >= d:
        break
    A[i] = d

print(sum(A))


n, m = map(int, input().split())
a = list(map(int, input().split()))
bc = [tuple(map(int, input().split())) for _ in range(m)]
a.sort()
bc.sort(reverse=True, key=lambda x: x[1])
last_idx = len(a) - 1
idx = 0
for e in bc:
    b, c = e
    for i in range(b):
        if i + idx > last_idx:
            break
        if a[i + idx] < c:
            a[i + idx] = c
        else:
            break
    else:
        idx += b
        print(a)
        print(idx)
        continue
    break

print(sum(a))

n, m = map(int, input().split())
a = list(map(int, input().split()))
bc = [tuple(map(int, input().split())) for _ in range(m)]
a.sort()
bc.sort(reverse=True, key=lambda x: x[1])
last_idx = len(a) - 1
idx = 0
for e in bc:
    b, c = e
    for i in range(b):
        if i + idx > last_idx:
            break
        if a[i + idx] < c:
            a[i + idx] = c
    idx += b

print(sum(a))


import sys

N, M = map(int, input().split())
A = list(map(int, input().split()))

ope = [tuple(map(int, x.split())) for x in sys.stdin.readlines()]

ope.sort(key=lambda x: -x[1])

cnt = 0
for b, c in ope:
    A = A + [c] * b
    cnt += b

    if cnt >= N:
        break

A.sort(reverse=True)

print(sum(A[:N]))

import sys

N, M = map(int, input().split())
A = list(map(int, input().split()))
A.sort(reverse=True)

ope = [list(map(int, x.split())) for x in sys.stdin.readlines()]

ope.sort(key=lambda x: -x[1])

mp = 0
ap = 0
cnt = 0
ans = 0

while cnt < N:
    a = A[ap]
    m = ope[mp][1] if mp < M else 0

    if m >= a:
        mc = min(ope[mp][0], N - cnt)
        ans += m * mc
        cnt += mc
        mp += 1
    else:
        ans += a
        cnt += 1
        ap += 1

print(ans)


import heapq

N, M = map(int, input().split())
A = list(map(int, input().split()))
origin = sum(A)
heapq.heapify(A)

for _ in range(M):
    b, c = map(int, input().split())
    for _ in range(b):
        smallest = heapq.heappop(A)
        tmp = c - smallest
        if tmp <= 0:
            heapq.heappush(A, smallest)
            break
        else:
            heapq.heappush(A, c)
            origin += tmp

print(origin)

import sys
import heapq

N, M = map(int, input().split())
A = list(map(int, input().split()))
origin = sum(A)
heapq.heapify(A)

BC = [list(map(int, input().split())) for _ in range(M)]
BC = sorted(BC, reverse=True, key=lambda x: x[1])

count = 0

for i in range(M):
    b = BC[i][0]
    c = BC[i][1]
    for _ in range(b):
        smallest = heapq.heappop(A)
        tmp = c - smallest
        if tmp <= 0:
            heapq.heappush(A, smallest)
            break
        else:
            heapq.heappush(A, c)
            origin += tmp
            count += 1
            if count >= N:
                print(origin)
                sys.exit()

print(origin)


N, M = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
BC = [list(map(int, input().split())) for i in range(M)]
BC = sorted(BC, key=lambda x: -x[1])
i = 0
for B, C in BC:
    for _ in range(B):
        if A[i] < C:
            A[i] = C
            i += 1
        else:
            print(sum(A))
            exit()
print(sum(A))

N, M = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
BC = [list(map(int, input().split())) for i in range(M)]
BC = sorted(BC, key=lambda x: -x[1])
i = 0
for B, C in BC:
    for _ in range(B):
        if i < N and A[i] < C:
            A[i] = C
            i += 1
        else:
            print(sum(A))
            exit()
print(sum(A))


n, m = map(int, input().split())
a_list = list(map(int, input().split()))
bc_list = [list(map(int, input().split())) for _ in range(m)]
a_list.sort()
bc_list.sort(key=lambda i: -i[1])

a_idx = 0
bc_idx = 0
while bc_idx < len(bc_list):
    b, c = bc_list[bc_idx]
    finish = False
    for _ in range(b):
        if c > a_list[a_idx]:
            a_list[a_idx] = c
            a_idx += 1
        else:
            finish = True
            break
    if finish:
        break
    bc_idx += 1

print(sum(a_list))

n, m = map(int, input().split())
a_list = list(map(int, input().split()))
bc_list = [list(map(int, input().split())) for _ in range(m)]
a_list.sort()
bc_list.sort(key=lambda i: -i[1])

a_idx = 0
bc_idx = 0
while bc_idx < len(bc_list):
    b, c = bc_list[bc_idx]
    finish = False
    for _ in range(b):
        if a_idx >= len(a_list):
            finish = True
            break
        if c > a_list[a_idx]:
            a_list[a_idx] = c
            a_idx += 1
        else:
            finish = True
            break
    if finish:
        break
    bc_idx += 1

print(sum(a_list))


def main():
    N, M = map(int, input().split())
    A = sorted(list(map(int, input().split())))
    BC = []
    for _ in range(M):
        B, C = map(int, input().split())
        BC.append((B, C))
    BC = sorted(BC, key=lambda x: x[1], reverse=True)
    i = 0
    for b, c in BC:
        for _ in range(b):
            if A[i] >= c:
                break
            A[i] = c
            i += 1
    print(sum(A))

main()

def main():
    N, M = map(int, input().split())
    A = sorted(list(map(int, input().split())))
    BC = []
    for _ in range(M):
        B, C = map(int, input().split())
        BC.append((B, C))
    BC = sorted(BC, key=lambda x: x[1], reverse=True)
    i = 0
    for b, c in BC:
        for _ in range(b):
            if i >= len(A) or A[i] >= c:
                break
            A[i] = c
            i += 1
    print(sum(A))

main()


from sys import stdin, setrecursionlimit
from heapq import heapify, heappop, heappush

def main():
    input = stdin.buffer.readline
    n, m = map(int, input().split())
    a = list(map(int, input().split()))
    heapify(a)

    for _ in range(m):
        b, c = map(int, input().split())
        for _ in range(b):
            ai = heappop(a)
            if ai < c:
                heappush(a, c)
            else:
                heappush(a, ai)
                break

    print(sum(a))

if __name__ == "__main__":
    setrecursionlimit(10000)
    main()

from sys import stdin, setrecursionlimit
from heapq import heapify, heappop, heappush

def main():
    input = stdin.buffer.readline
    n, m = map(int, input().split())
    a = list(map(int, input().split()))
    bc = [list(map(int, input().split())) for _ in range(m)]
    bc.sort(key=lambda x: -x[1])
    heapify(a)

    for i in range(m):
        b, c = bc[i]
        for _ in range(b):
            ai = heappop(a)
            if ai < c:
                heappush(a, c)
            else:
                heappush(a, ai)
                break

    print(sum(a))

if __name__ == "__main__":
    setrecursionlimit(10000)
    main()


import bisect

n, m = map(int, input().split())
arr = list(sorted(list(map(int, input().split()))))
bc = []
for _ in range(m):
    b, c = map(int, input().split())
    bc.append([b, c])

bc = list(sorted(bc, key=lambda x: x[1], reverse=True))
ans = 0

for bci in bc:
    d = bisect.bisect_left(arr, bci[1])
    arr = arr[min(d, bci[0]) :]
    ans += min(d, bci[0]) * bci[1]
print(ans + sum(arr))

# 書き換える枚数は確定できる
# cの大きい順にしたものでaの小さい順にしたものを置き換えるイメージ
# なんか尺取っぽくなった

n, m = map(int, input().split())
arr = sorted(list(map(int, input().split())))

bcs = []
for _ in range(m):
    bc = list(map(int, input().split()))
    bcs.append(bc)

bcs = sorted(bcs, key=lambda x: x[1], reverse=True)
ans = 0

i = 0
for b in bcs:
    while i < n and arr[i] < b[1] and b[0] > 0:
        ans += b[1]
        b[0] -= 1
        i += 1
print(ans + sum(arr[i:]))


n, m = map(int, input().split())
A = sorted(list(map(int, input().split())))
C = []
for _ in range(m):
    b, c = map(int, input().split())
    C.extend([c] * b)
C = sorted(C, reverse=True)

ans = 0
for i in range(n):
    try:
        ans += max(A[i], C[i])
    except IndexError:
        ans += A[i]

print(ans)

n, m = map(int, input().split())
A = sorted(list(map(int, input().split())))
BC = sorted(
    [list(map(int, input().split())) for _ in range(m)], key=lambda x: x[1], reverse=True
)

ans = 0
j = 0
for b, c in BC:
    for i in range(b):
        if j < n:
            ans += max(c, A[j])
            j += 1
        else:
            break

if j < n:
    for i in range(n - j):
        ans += A[n - 1 - i]

print(ans)


n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
bc = [[0] * 2] * m

for i in range(m):
    bc[i] = list(map(int, input().split()))

a.sort()
bc = sorted(bc, key=lambda x: -x[1])
new = []

for e in bc:
    new.extend([e[1]] * e[0])

for i in range(min(n, len(new))):
    a[i] = max(a[i], new[i])

print(sum(a))

n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
bc = [[0] * 2] * m

for i in range(m):
    bc[i] = list(map(int, input().split()))

a.sort()
bc = sorted(bc, key=lambda x: -x[1])
new = []

cnt = 0

for e in bc:
    new += [e[1]] * e[0]
    cnt += e[0]

    if n <= cnt:
        break

for i in range(min(n, cnt)):
    a[i] = max(a[i], new[i])

print(sum(a))


N, M = map(int, input().split())
A_list = list(map(int, input().split()))
A_list.sort()

BC_list = [list(map(int, input().split())) for _ in range(M)]
BC_list = [BC_list[i][1] for i in range(M) for _ in range(BC_list[i][0])]
A_list.extend(BC_list)
A_list.sort()

print(sum(A_list[-N:]))

N, M = map(int, input().split())
A_list = list(map(int, input().split()))
A_list.sort()

BC_list = [list(map(int, input().split())) for _ in range(M)]
BC_list = sorted(BC_list, key=lambda x: x[1])

ans = 0
count = 0
i = N - 1
m = M - 1
while count < N:
    if A_list[i] < BC_list[m][1]:
        for _ in range(BC_list[m][0]):
            ans += BC_list[m][1]
            count += 1
            if count >= N:
                break
        m -= 1
    else:
        ans += A_list[i]
        count += 1
        i -= 1

    if m < 0:
        break

for _ in range(count, N):
    ans += A_list[i]
    i -= 1

print(ans)


import sys

n, m = list(map(int, input().split()))
aaa = list(map(int, input().split()))
for line in sys.stdin:
    b, c = list(map(int, line.split()))
    aaa = sorted(aaa + [c] * b, reverse=True)[:n]
print(sum(aaa))

import sys

n, m = list(map(int, input().split()))
aaa = list(map(int, input().split()))
aaa.sort()
bc = []
for line in sys.stdin:
    b, c = map(int, line.split())
    bc.append((c, b))
bc.sort(reverse=True)
ans = 0
cnt = 0
for c, b in bc:
    while aaa and aaa[-1] >= c and cnt < n:
        ans += aaa.pop()
        cnt += 1
    if cnt + b >= n:
        ans += c * (n - cnt)
        cnt = n
        break
    ans += c * b
    cnt += b
if cnt < n:
    ans += sum(aaa[cnt - n :])
print(ans)


N, M = map(int, input().split())
As = list(map(int, input().split()))

for _ in range(M):
    As.sort()
    b, c = map(int, input().split())
    for i in range(b):
        if As[i] < c:
            As[i] = c
        else:
            break

print(sum(As))

N, M = map(int, input().split())
As = list(map(int, input().split()))
As.sort(reverse=True)

BCs = []
for _ in range(M):
    b, c = map(int, input().split())
    BCs.append({"b": b, "c": c})

BCs = sorted(BCs, key=lambda bc: bc["c"], reverse=True)
# print(BCs)

new_cards = []
for i in range(M):
    new_cards += [BCs[i]["c"] for _ in range(BCs[i]["b"])]
    if len(new_cards) >= N:
        break

if len(new_cards) < N:
    new_cards += [0 for _ in range(N - len(new_cards))]
# print(new_cards)

A_index = 0
new_index = 0
new_As = []
for i in range(N):
    if As[A_index] >= new_cards[new_index]:
        new_As.append(As[A_index])
        A_index += 1
    else:
        new_As.append(new_cards[new_index])
        new_index += 1

print(sum(new_As))


[n, m] = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]

for i in range(m):
    [b, c] = [int(i) for i in input().split()]
    a += [c for i in range(b)]

a.sort(reverse=True)
print(sum(a[:n]))

[n, m] = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
l = [[int(j) for j in input().split()] for i in range(m)]
l.sort(reverse=True, key=lambda x: x[1])

k = []
for i in l:
    k += [i[1]] * i[0]
    if len(k) >= n:
        break

k += a
k.sort(reverse=True)
print(sum(k[:n]))


n, m = map(int, input().split())
a = sorted(list(map(int, input().split())))
mat = []
for _ in range(m):
    b, c = map(int, input().split())
    mat.extend([c] * b)
mat = sorted(mat, reverse=True)[:n]
for i, t in enumerate(a):
    if i == len(mat):
        break
    if t < mat[i]:
        a[i] = mat[i]
    else:
        break

print(sum(a))

n, m = map(int, input().split())
a = sorted(list(map(int, input().split())))
bc = [[0] * 2 for _ in range(m)]
for i in range(m):
    bc[i] = list(map(int, input().split()))
bc = sorted(bc, key=lambda x: x[1], reverse=True)
mat = []
for b, c in bc:
    if len(mat) + b > n:
        mat.extend([c] * (n - len(mat)))
        break
    else:
        mat.extend([c] * b)

for i, t in enumerate(a):
    if i == len(mat):
        break
    if t < mat[i]:
        a[i] = mat[i]
    else:
        break

print(sum(a))


import sys

N, M = map(int, input().split())
A = list(map(int, sys.stdin.readline().rsplit()))
A.sort()
C = []

for _ in range(M):
    b, c = map(int, input().split())
    C.extend([c] * b)

C.sort(reverse=True)

res = 0
for i in range(N):
    if i < len(C):
        if A[i] < C[i]:
            res += C[i]
        else:
            res += A[i]
    else:
        res += A[i]
print(res)

import sys

N, M = map(int, input().split())
A = list(map(int, sys.stdin.readline().rsplit()))
BC = [list(map(int, sys.stdin.readline().rsplit())) for _ in range(M)]
A.sort()
BC.sort(reverse=True, key=lambda x: x[1])
C = []

for b, c in BC:
    if len(C) >= N:
        break
    for _ in range(b):
        C.append(c)

C.sort(reverse=True)

res = 0
lenC = len(C)
for i in range(N):
    if i < lenC and A[i] < C[i]:
        res += C[i]
    else:
        res += A[i]
print(res)


import bisect

N, M = map(int, input().split())
A = sorted(list(map(int, input().split())))

BC = []
for _ in range(M):
    b, c = map(int, input().split())
    BC.append((b, c))

BC.sort(reverse=True, key=lambda x: x[1])

ans, i = 0, 0
for bc in BC:
    ti = bisect.bisect(A[i:], bc[1]) + i
    if (ti > i) and (bc[0] >= (ti - i)):
        ans += bc[1] * (ti - i)
        i = ti
    elif (ti > i) and (bc[0] < (ti - i)):
        ans += bc[1] * bc[0]
        i = i + bc[0]

print(ans + sum(A[i:]))

import bisect

N, M = map(int, input().split())
A = sorted(list(map(int, input().split())))

BC = []
for _ in range(M):
    b, c = map(int, input().split())
    BC.append((b, c))

BC.sort(reverse=True, key=lambda x: x[1])

ans, i = 0, 0
for bc in BC:
    ti = bisect.bisect(A, bc[1])
    if (ti > i) and (bc[0] >= (ti - i)):
        ans += bc[1] * (ti - i)
        i = ti
    elif (ti > i) and (bc[0] < (ti - i)):
        ans += bc[1] * bc[0]
        i = i + bc[0]

print(ans + sum(A[i:]))


import sys

fin = sys.stdin.readline

N, M = map(int, fin().split())
As = list(map(int, fin().split()))
BC = [tuple(map(int, fin().split())) for _ in range(M)]

As = sorted(As)
# BC = sorted(BC, key=lambda x: x[1], reverse=True)

BC_ = {}
for num, val in BC:
    if val in BC_:
        BC_[val] += num
    else:
        BC_[val] = num

BC_ = sorted(BC_.items(), reverse=True)

#
# def f(a, n, v):
#     if a[min(n-1, len(a)-1)] < v:
#         return v * min(n, len(a)), a[n:]
#     count = 0
#     for i in range(min(n, len(a))):
#         if a[i] < v:
#             count += 1
#         else:
#             break
#     return v * count, a[count:]

sum__ = 0
for val, num in BC_:
    if len(As) == 0 or As[0] >= val:
        break

    if As[min(num - 1, len(As) - 1)] < val:
        sum_, As = val * min(num, len(As)), As[num:]
    else:
        count = 0
        for i in range(min(num, len(As))):
            if As[i] < val:
                count += 1
            else:
                break
        sum_, As = val * count, As[count:]
    sum__ += sum_

print(sum__ + sum(As))

import sys

fin = sys.stdin.readline

N, M = map(int, fin().split())
As = list(map(int, fin().split()))
BC = [tuple(map(int, fin().split())) for _ in range(M)]

As = sorted(As)
# BC = sorted(BC, key=lambda x: x[1], reverse=True)

BC_ = {}
for num, val in BC:
    if val in BC_:
        BC_[val] += num
    else:
        BC_[val] = num

BC_ = sorted(BC_.items(), reverse=True)

#
# def f(a, n, v):
#     if a[min(n-1, len(a)-1)] < v:
#         return v * min(n, len(a)), a[n:]
#     count = 0
#     for i in range(min(n, len(a))):
#         if a[i] < v:
#             count += 1
#         else:
#             break
#     return v * count, a[count:]

sum__ = 0
now = 0
for val, num in BC_:
    if now >= len(As) or As[now] >= val:
        break

    if As[min(num - 1 + now, len(As) - 1)] < val:
        sum_ = val * min(num, len(As) - now)
        now += min(num, len(As) - now)
    else:
        count = 0
        for i in range(min(num, len(As) - now)):
            if As[i + now] < val:
                count += 1
            else:
                break
        sum_ = val * count
        now += count
    sum__ += sum_

print(sum__ + sum(As[now:]))


import heapq

n, m = map(int, input().split())
a = list(map(int, input().split()))
heapq.heapify(a)
bc = [list(map(int, input().split())) for _ in range(m)]
for b, c in bc:
    for _ in range(b):
        x = heapq.heappop(a)
        if c > x:
            heapq.heappush(a, c)
        else:
            heapq.heappush(a, x)
print(sum(a))

import heapq

n, m = map(int, input().split())
a = list(map(int, input().split()))
heapq.heapify(a)
bc = [list(map(int, input().split())) for _ in range(m)]
bc = sorted(bc, key=lambda x: -x[1])
for b, c in bc:
    for _ in range(b):
        x = heapq.heappop(a)
        if c > x:
            heapq.heappush(a, c)
        else:
            heapq.heappush(a, x)
            break
print(sum(a))


def resolve():
    n, m = list(map(int, input().split()))
    a = list(map(int, input().split()))
    bc = list(list(map(int, input().split())) for _ in range(m))
    for b, c in bc:
        a += [c for _ in range(b)]
    print(sum(sorted(a, reverse=True)[:n]))

if __name__ == "__main__":
    resolve()

def resolve():
    n, m = list(map(int, input().split()))
    a = list(map(int, input().split()))
    bc = list(list(map(int, input().split())) for _ in range(m))
    pairs = [(ai, 1) for ai in a]
    for b, c in bc:
        pairs.append((c, b))
    pairs.sort(key=lambda x: x[0], reverse=True)
    c = 0
    ans = 0
    for v, num in pairs:
        if c + num <= n:
            ans += v * num
            c += num
        else:
            ans += v * (n - c)
            break
    print(ans)

if __name__ == "__main__":
    resolve()


from heapq import heappush, heappushpop

Q = int(input())

b = 0
la = []
sl = 0
ra = []
sr = 0

cnt = 0
for _ in range(Q):
    q = map(int, input().split())
    # print(la, ra)
    if q[0] == 2:
        # 求値
        x = -la[0]
        cl = (cnt + 1) // 2
        cr = cnt - cl
        print(x, (cl * x - sl) + (sr - cr * x) + b)
    else:
        # 更新
        b += q[2]
        cnt += 1
        if cnt % 2 == 1:
            sr += q[1]
            x = heappushpop(ra, q[1])
            sr -= x
            sl += x
            heappush(la, -x)
        else:
            sl += q[1]
            x = heappushpop(la, -q[1])
            x *= -1
            sl -= x
            sr += x
            heappush(ra, x)

from heapq import heappush, heappushpop

Q = int(input())

b = 0
la = []
sl = 0
ra = []
sr = 0

cnt = 0
for _ in range(Q):
    q = tuple(map(int, input().split()))
    # print(la, ra)
    if q[0] == 2:
        # 求値
        x = -la[0]
        cl = (cnt + 1) // 2
        cr = cnt - cl
        print(x, (cl * x - sl) + (sr - cr * x) + b)
    else:
        # 更新
        b += q[2]
        cnt += 1
        if cnt % 2 == 1:
            sr += q[1]
            x = heappushpop(ra, q[1])
            sr -= x
            sl += x
            heappush(la, -x)
        else:
            sl += q[1]
            x = heappushpop(la, -q[1])
            x *= -1
            sl -= x
            sr += x
            heappush(ra, x)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03040/Python/s771493021.py", line 15, in <module>
    if q[0] == 2:
TypeError: 'map' object is not subscriptable


# -*- coding: utf-8 -*-
from heapq import heappush, heappop

qn = int(input())

low = []
high = []
ans = 0
num = 0

for i in range(qn):
    q = [int(i) for i in input().split()]
    if q[0] == 1:
        ans += q[2]
        a = q[1]
        if a < -low[0]:
            ans += -low[0] - a
        elif a > high[0]:
            ans += a - high[0]

        # lowは降順に並べたいので-aを入れる
        heappush(low, -a)
        heappush(high, a)
        if -low[0] > high[0]:
            low0 = heappop(low)
            high0 = heappop(high)
            # lowとhighで正負が逆なので注意する
            heappush(low, -high0)
            heappush(high, -low0)
    elif q[0] == 2:
        print(-low[0], ans)

# -*- coding: utf-8 -*-
from heapq import heappush, heappop

qn = int(input())

low = []
high = []
ans = 0

for i in range(qn):
    q = [int(i) for i in input().split()]
    if q[0] == 1:
        ans += q[2]
        a = q[1]

        if len(low) >= 1:
            if a < -low[0]:
                ans += -low[0] - a
            elif a > high[0]:
                ans += a - high[0]

        # lowは降順に並べたいので-aを入れる
        heappush(low, -a)
        heappush(high, a)
        if -low[0] > high[0]:
            low0 = heappop(low)
            high0 = heappop(high)
            # lowとhighで正負が逆なので注意する
            heappush(low, -high0)
            heappush(high, -low0)

    elif q[0] == 2:
        print(-low[0], ans)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03040/Python/s610424106.py", line 16, in <module>
    if a < -low[0]:
IndexError: list index out of range


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

print(s.replace(s[k], s[k].lower()))

n, k = map(int, input().split())
s = input()
print(s[: k - 1] + s[k - 1].lower() + s[k:])


n, k = map(int, input().split())
s = list(input())
s[k] = s[k].lower()
print("".join(s))

n, k = map(int, input().split())
s = list(input())
s[k - 1] = s[k - 1].lower()
print("".join(s))


N, K = map(int, input().split())
S = str(input())
if S[K - 1] == "A":
    S[K - 1] = "a"
    print("".join(S))
elif S[K - 1] == "B":
    S[K - 1] = "b"
    print("".join(S))
else:
    S[K - 1] = "c"
    print("".join(S))

N, K = map(int, input().split())
S = list(input())
if S[K - 1] == "A":
    S[K - 1] = "a"
    print("".join(S))
elif S[K - 1] == "B":
    S[K - 1] = "b"
    print("".join(S))
else:
    S[K - 1] = "c"
    print("".join(S))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03041/Python/s243214892.py", line 4, in <module>
    S[K - 1] = "a"
TypeError: 'str' object does not support item assignment


n, k = map(int, input().split())
s = input()
s[k - 1] = s[k - 1].lower()
print(s)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03041/Python/s255611980.py", line 3, in <module>
    s[k - 1] = s[k - 1].lower()
TypeError: 'str' object does not support item assignment


def ismonth(month):
    return 0 < month < 13

S = input()

former = int(S[:2])
latter = int(S[2:])

if former < 1 or latter < 1:
    ans = "NA"

elif ismonth(former) and ismonth(latter):
    ans = "AMBIGUOUS"

elif ismonth(former):
    ans = "MMYY"

elif ismonth(latter):
    ans = "YYMM"

print(ans)

from datetime import datetime

S = input()
former = int(S[:2])
latter = int(S[2:])
YYMM = False
MMYY = False

try:
    datetime(former + 2000, latter, 1)
    YYMM = True
except:
    pass

try:
    datetime(latter + 2000, former, 1)
    MMYY = True
except:
    pass

if YYMM and MMYY:
    print("AMBIGUOUS")
elif YYMM:
    print("YYMM")
elif MMYY:
    print("MMYY")
else:
    print("NA")


a = input()
b = int(a[:2])
c = int(a[2:])
if 0 < b <= 12 and a < c <= 12:
    print("AMBIGUOUS")
elif 0 < b <= 12 and c > 12:
    print("MMYY")
elif b > 12 and 0 < c <= 12:
    print("YYMM")
else:
    print("NA")

a = input()
b = int(a[:2])
c = int(a[2:])
if 0 < b <= 12 and 0 < c <= 12:
    print("AMBIGUOUS")
elif 0 < b <= 12:
    print("MMYY")
elif 0 < c <= 12:
    print("YYMM")
else:
    print("NA")


#!/usr/bin/env python3
import sys

def solve(S: int):

    S = str(S)

    if int(S[:2]) > 12 and 1 <= int(S[2:]) <= 12:
        print("YYMM")
    elif 1 <= int(S[:2]) <= 12 and int(S[2:]) > 12:
        print("MMYY")
    elif 1 <= int(S[:2]) <= 12 and 1 <= int(S[2:]) <= 12:
        print("AMBIGUOUS")
    else:
        print("NA")

    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word

    tokens = iterate_tokens()
    S = int(next(tokens))  # type: int
    solve(S)

if __name__ == "__main__":
    main()

#!/usr/bin/env python3
import sys

def solve(S: int):

    if 1 <= int(S[2:]) <= 12:
        if 1 <= int(S[:2]) <= 12:
            print("AMBIGUOUS")
        else:
            print("YYMM")
    else:
        if 1 <= int(S[:2]) <= 12:
            print("MMYY")
        else:
            print("NA")

    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word

    tokens = iterate_tokens()
    S = str(next(tokens))  # type: int
    solve(S)

if __name__ == "__main__":
    main()


import math

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

for i in range(1, min(K, N + 1)):
    print(math.ceil(math.log2(K / i)))
    p += 2 ** (-math.ceil(math.log2(K / i)))

p += max(0, N - K + 1)
print(p / N)

import math

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

count = 1
while True:
    p += (
        max(0, min(N + 1, math.ceil(K / 2 ** (count - 1))) - math.ceil(K / 2**count))
        * 0.5**count
    )
    count += 1
    if K / 2**count < 0.5:
        break

p += max(0, N - K + 1)
print(p / N)


import decimal

def main():
    N, K = map(int, input().split())
    s = N
    c = 0
    while K > s:
        s *= 2
        c += 1
    cp = (1 / 2) ** c
    ans = decimal.Decimal((1 / N) * cp)
    cc = c
    for n in range(N - 1, 0, -1):
        s = n
        c = 0
        while K > s:
            s *= 2
            c += 1
        cp *= 1 / 2 ** (c - cc)
        ans += decimal.Decimal((1 / N) * cp)
        cc = c
    print(ans)

main()

import decimal

def main():
    N, K = map(int, input().split())
    ans = 0
    for n in range(1, N + 1):
        s = 0
        s += n
        c = 0
        while K > s:
            s *= 2
            c += 1
        ans += decimal.Decimal((1 / N) * (1 / 2) ** c)
    print(ans)

main()


import decimal

def main():
    N, K = map(int, input().split())
    ans = 0
    for n in range(1, N + 1):
        s = n
        c = 1
        while K > s:
            s *= 2
            c /= 2
        ans += decimal.Decimal((1 / N) * c)
    print(ans)

main()

def main():
    N, K = map(int, input().split())
    ans = 0
    for n in range(1, N + 1):
        s = n
        c = 1
        while K > s:
            s *= 2
            c /= 2
        ans += (1 / N) * c
    print(ans)

main()


from decimal import Decimal

n, k = map(int, input().split())
sum = Decimal(0.0)
for i in range(1, n + 1):
    p = Decimal(1.0 / n)
    score = i
    while score < k:
        score = score * 2
        p = p * Decimal(0.5)
    sum += p
print(str(sum)[:14])

n, k = map(int, input().split())
sum = 0.0
for i in range(1, n + 1):
    p = 1.0 / n
    score = i
    while score < k:
        score = score * 2
        p = p * 0.5
    sum += p
print(sum)