x, y, a, b, c = map(int, input().split())
p = sorted(map(int, input().split()))
q = sorted(map(int, input().split()))
r = sorted(map(int, input().split()), reverse=True)
pi = len(p) - x
qi = len(q) - y
ri = 0
for _ in range(len(r)):
    if r[ri] <= min(p[pi], q[qi]):
        break
    else:
        if pi >= len(p) and qi >= len(q):
            break
        else:
            if pi < len(p) and qi < len(q):
                if p[pi] < q[qi]:
                    p[pi] = r[ri]
                    pi += 1
                else:
                    q[qi] = r[ri]
                    qi += 1
            elif pi >= len(p) and qi < len(q):
                if q[qi] < r[ri]:
                    q[qi] = r[ri]
                    qi += 1
            elif pi < len(p) and qi >= len(q):
                if p[pi] < r[ri]:
                    p[pi] = r[ri]
                    pi += 1
            ri += 1
            continue
print(sum(p[-x:]) + sum(q[-y:]))

x, y, a, b, c = map(int, input().split())
p = sorted(map(int, input().split()))
q = sorted(map(int, input().split()))
r = sorted(map(int, input().split()), reverse=True)
pi = len(p) - x
qi = len(q) - y
ri = 0
for _ in range(len(r)):
    if r[ri] <= min(p[min(pi, len(p) - 1)], q[min(qi, len(q) - 1)]):
        break
    else:
        if pi >= len(p) and qi >= len(q):
            break
        else:
            if pi < len(p) and qi < len(q):
                if p[pi] < q[qi]:
                    p[pi] = r[ri]
                    pi += 1
                else:
                    q[qi] = r[ri]
                    qi += 1
            elif pi < len(p) and qi >= len(q):
                p[pi] = r[ri]
                pi += 1
            else:
                q[qi] = r[ri]
                qi += 1
            ri += 1
print(sum(p[-x:]) + sum(q[-y:]))


X, Y, A, B, C = map(int, input().split())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
R = list(map(int, input().split()))

P.sort(reverse=True)
Q.sort(reverse=True)
R.sort(reverse=True)

S = P[:X] + Q[:Y]
S.sort(reverse=True)

S_wa = []
wa = 0
for s in S[::-1]:
    wa += s
    S_wa.append(wa)
# print(S_wa)
big = S_wa[-1]
ans = S_wa[-1]

R_wa = []
wa = 0
for r in R:
    wa += r
    R_wa.append(wa)
# print(R_wa)

for i in range(len(R_wa)):
    ans = max(ans, big + R_wa[i] - S_wa[i])
print(ans)

X, Y, A, B, C = map(int, input().split())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
R = list(map(int, input().split()))

P.sort(reverse=True)
Q.sort(reverse=True)
R.sort(reverse=True)

S = P[:X] + Q[:Y]
S.sort(reverse=True)

S_wa = []
wa = 0
for s in S[::-1]:
    wa += s
    S_wa.append(wa)
# print(S_wa)
big = S_wa[-1]
ans = S_wa[-1]

R_wa = []
wa = 0
for r in R:
    wa += r
    R_wa.append(wa)
# print(R_wa)

kazu = min(len(R_wa), len(S_wa))

for i in range(kazu):
    ans = max(ans, big + R_wa[i] - S_wa[i])
print(ans)


from heapq import heapify, heappushpop

X, Y, A, B, C = map(int, input().split())
# 大きい順にソートして受け取っておく
p = sorted(list(map(int, input().split())))[::-1]
q = sorted(list(map(int, input().split())))[::-1]
r = sorted(list(map(int, input().split())))[::-1]
ans_list = p[:X] + q[:Y]  # 着色しない場合
heapify(ans_list)
m = min(ans_list)
for ri in r:
    if ri > m:
        heappushpop(ans_list, ri)
        m = min(ans_list)
    else:
        break
print(sum(ans_list))

from heapq import heapify, heappushpop

X, Y, A, B, C = map(int, input().split())
# 大きい順にソートして受け取っておく
p = sorted(list(map(int, input().split())))[::-1]
q = sorted(list(map(int, input().split())))[::-1]
r = sorted(list(map(int, input().split())))[::-1]
ans_list = p[:X] + q[:Y]  # 着色しない場合
heapify(ans_list)
for ri in r:
    if ri > ans_list[0]:
        heappushpop(ans_list, ri)
    else:
        break
print(sum(ans_list))


x, y, a, b, c = map(int, input().split())
p = sorted(list(map(int, input().split())), reverse=True)
pp = p[:]
q = sorted(list(map(int, input().split())), reverse=True)
qq = q[:]
r = sorted(list(map(int, input().split())), reverse=True)
rr = r[:]
ans1 = 0
for _ in range(x):
    if len(p) > 0 and len(r) > 0:
        if p[0] >= r[0]:
            ans1 += p.pop(0)
        else:
            ans1 += r.pop(0)
    elif len(p) > 0:
        ans1 += p.pop(0)
    else:
        ans1 += r.pop(0)
for _ in range(y):
    if len(q) > 0 and len(r) > 0:
        if q[0] >= r[0]:
            ans1 += q.pop(0)
        else:
            ans1 += r.pop(0)
    elif len(q) > 0:
        ans1 += q.pop(0)
    else:
        ans1 += r.pop(0)

ans2 = 0
for _ in range(y):
    if len(qq) > 0 and len(rr) > 0:
        if qq[0] >= rr[0]:
            ans2 += qq.pop(0)
        else:
            ans2 += rr.pop(0)
    elif len(qq) > 0:
        ans2 += qq.pop(0)
    else:
        ans2 += rr.pop(0)
for _ in range(x):
    if len(pp) > 0 and len(rr) > 0:
        if pp[0] >= rr[0]:
            ans2 += pp.pop(0)
        else:
            ans2 += rr.pop(0)
    elif len(pp) > 0:
        ans2 += pp.pop(0)
    else:
        ans2 += rr.pop(0)
print(max(ans1, ans2))

x, y, a, b, c = map(int, input().split())
p = sorted(list(map(int, input().split())), reverse=True)
pp = p[:x]
q = sorted(list(map(int, input().split())), reverse=True)
qq = q[:y]
r = list(map(int, input().split()))

l = pp + qq + r
l.sort(reverse=True)
print(sum(l[: (x + y)]))


from collections import deque

X, Y, A, B, C = map(int, input().split())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
r = list(map(int, input().split()))

p.sort(reverse=True)
q.sort(reverse=True)
r.sort(reverse=True)

p = deque(p)
q = deque(q)
r = deque(r)

ans = 0
for _ in range(X):
    if p[0] >= r[0]:
        ans += p.popleft()
    else:
        ans += r.popleft()
for _ in range(Y):
    if q[0] >= r[0]:
        ans += q.popleft()
    else:
        ans += r.popleft()

print(ans)

X, Y, A, B, C = map(int, input().split())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
r = list(map(int, input().split()))

p.sort(reverse=True)
q.sort(reverse=True)
r.sort(reverse=True)

p = p[:X]
q = q[:Y]

all = p + q + r
all.sort(reverse=True)
ans = sum(all[: X + Y])
print(ans)


x, y, a, b, c = map(int, input().split())
P = sorted(list(map(int, input().split())), reverse=True)
Q = sorted(list(map(int, input().split())), reverse=True)
R = sorted(list(map(int, input().split())))

A = sorted(P[:x] + Q[:y])
ans = sum(A)

for i in range(c):
    if A[i] < R[-1]:
        ans = ans + R[-1] - A[i]
        R.pop(-1)

print(ans)

x, y, a, b, c = map(int, input().split())
P = sorted(list(map(int, input().split())), reverse=True)
Q = sorted(list(map(int, input().split())), reverse=True)
R = sorted(list(map(int, input().split())))

A = sorted(P[:x] + Q[:y])
ans = sum(A)

for i in range(min(c, len(A))):
    if A[i] < R[-1]:
        ans = ans + R[-1] - A[i]
        R.pop(-1)

print(ans)


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

X, Y, A, B, C = map(int, input().split())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
r = list(map(int, input().split()))

# all_apples = sorted(p + q + r, key=lambda x: -x)

p_rest = sorted(p)
q_rest = sorted(q)
r_rest = sorted(r)

ans = 0
p_count = 0
q_count = 0
r_count = 0
while (p_count + q_count + r_count) < (X + Y):
    if p_count < X and q_count < Y:
        candidates = [p_rest[-1], q_rest[-1], r_rest[-1]]
    elif p_count < X and q_count == Y:
        candidates = [p_rest[-1], 0, r_rest[-1]]
    elif p_count == X and q_count < Y:
        candidates = [0, q_rest[-1], r_rest[-1]]

    wanna_eat = max(candidates)
    eat_idx = candidates.index(wanna_eat)

    if eat_idx == 0:
        p_count += 1
        ans += p_rest.pop()
    elif eat_idx == 1:
        q_count += 1
        ans += q_rest.pop()
    else:
        r_count += 1
        ans += r_rest.pop()
    # print(candidates, eat_idx, wanna_eat, p_count, q_count, r_count)

print(ans)

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

X, Y, A, B, C = map(int, input().split())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
r = list(map(int, input().split()))

# all_apples = sorted(p + q + r, key=lambda x: -x)

p_rest = sorted(p + [0])
q_rest = sorted(q + [0])
r_rest = sorted(r + [0])

ans = 0
p_count = 0
q_count = 0
r_count = 0
while (p_count + q_count + r_count) < (X + Y):
    if p_count < X and q_count < Y:
        candidates = [p_rest[-1], q_rest[-1], r_rest[-1]]
    elif p_count < X and q_count == Y:
        candidates = [p_rest[-1], 0, r_rest[-1]]
    elif p_count == X and q_count < Y:
        candidates = [0, q_rest[-1], r_rest[-1]]

    wanna_eat = max(candidates)
    eat_idx = candidates.index(wanna_eat)

    if eat_idx == 0:
        p_count += 1
        ans += p_rest.pop()
    elif eat_idx == 1:
        q_count += 1
        ans += q_rest.pop()
    else:
        r_count += 1
        ans += r_rest.pop()
    # print(candidates, eat_idx, wanna_eat, p_count, q_count, r_count)

print(ans)


x, y, a, b, c = map(int, input().split())
ps = list(map(int, input().split()))
qs = list(map(int, input().split()))
rs = list(map(int, input().split()))
ps.sort()
ps = ps[-x:]
qs.sort()
qs = qs[-y:]
pqs = ps + qs
pqs.sort()
rs.sort(reverse=True)

answer = sum(pqs)
for i in range(c):
    diff = rs[i] - pqs[i]
    if diff < 0:
        break
    answer += diff

print(answer)

x, y, a, b, c = map(int, input().split())
ps = list(map(int, input().split()))
qs = list(map(int, input().split()))
rs = list(map(int, input().split()))
ps.sort()
ps = ps[-x:]
qs.sort()
qs = qs[-y:]
pqs = ps + qs
pqs.sort()
rs.sort(reverse=True)

answer = sum(pqs)
for i in range(min(x + y, c)):
    diff = rs[i] - pqs[i]
    if diff < 0:
        break
    answer += diff

print(answer)


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

print(int(N * (N - 1) / 2 + M * (M - 1) / 2))

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

print(int(N * (N - 1) / 2 + M * (M - 1) / 2))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02729/Python/s321382416.py", line 1, in <module>
    N, M = list(int, input().split())
TypeError: list expected at most 1 argument, got 2


from scipy.special import comb

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

print(comb(n, 2, exact=True) + comb(m, 2, exact=True))

from math import factorial

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

if n > 2 and m > 2:
    print(
        factorial(n) // (factorial(n - 2) * factorial(2))
        + factorial(m) // (factorial(m - 2) * factorial(2))
    )
elif n < 2 and m < 2:
    print(0)
elif n < 2:
    print(factorial(m) // (factorial(m - 2) * factorial(2)))
elif m < 2:
    print(factorial(n) // (factorial(n - 2) * factorial(2)))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02729/Python/s504439278.py", line 1, in <module>
    from scipy.special import comb
ModuleNotFoundError: No module named 'scipy'


from math import factorial

n, m = map(int, input().split())
if n == 1 and m == 1:
    ans = 0
elif n == 1:
    ans = factorial(m) // (factorial(m - 2) * factorial(2))
elif m == 1:
    ans = factorial(n) // (factorial(n - 2) * factorial(2))
else:
    ans = factorial(n) // (factorial(n - 2) * factorial(2))
    ans += factorial(m) // (factorial(m - 2) * factorial(2))
print(ans)

from math import factorial

n, m = map(int, input().split())
if n in [0, 1] and m in [0, 1]:
    ans = 0
elif n in [0, 1]:
    ans = factorial(m) // (factorial(m - 2) * factorial(2))
elif m in [0, 1]:
    ans = factorial(n) // (factorial(n - 2) * factorial(2))
else:
    ans = factorial(n) // (factorial(n - 2) * factorial(2))
    ans += factorial(m) // (factorial(m - 2) * factorial(2))
print(ans)


import math

def f(x):
    return math.factorial(x)

arr = list(map(int, input().split()))
n = arr[0]
m = arr[1]
cnt = 0
cnt += int(f(n) / (2 * f(n - 2)))
if m > 1:
    cnt += int(f(m) / (2 * f(m - 2)))
print(int(cnt))


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

print(N(N - 1) // 2 + M(M - 1) // 2)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02729/Python/s193391695.py", line 3, in <module>
    print(N(N - 1) // 2 + M(M - 1) // 2)
TypeError: 'int' object is not callable


from math import factorial

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

if N == 0:
    combN = 0
else:
    combN = factorial(N) // (factorial(N - 2) * factorial(2))

if M == 0:
    combM = 0
else:
    combM = factorial(M) // (factorial(M - 2) * factorial(2))

print(combN + combM)

from math import factorial

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

if N <= 1:
    combN = 0
else:
    combN = factorial(N) // (factorial(N - 2) * factorial(2))

if M <= 1:
    combM = 0
else:
    combM = factorial(M) // (factorial(M - 2) * factorial(2))

print(combN + combM)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02729/Python/s805116877.py", line 13, in <module>
    combM = factorial(M) // (factorial(M - 2) * factorial(2))
ValueError: factorial() not defined for negative values


import math

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

def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

ans = combinations_count(m, 2) + combinations_count(n, 2)

print(ans)

import math

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

def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

if n >= 2 and m >= 2:
    ans = combinations_count(m, 2) + combinations_count(n, 2)
elif n < 2 and m < 2:
    ans = 0
elif n < 2:
    ans = combinations_count(m, 2)
elif m < 2:
    ans = combinations_count(n, 2)

print(ans)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02729/Python/s072089097.py", line 10, in <module>
    ans = combinations_count(m, 2) + combinations_count(n, 2)
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02729/Python/s072089097.py", line 7, in combinations_count
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
ValueError: factorial() not defined for negative values


# -*- coding: utf-8 -*-
# モジュールのインポート
from scipy.special import comb

# 標準入力の取得
N, M = list(map(int, input().split()))

# 求解処理
result = comb(N, 2, exact=True) + comb(M, 2, exact=True)

# 結果出力
print(result)

# -*- coding: utf-8 -*-
# 標準入力の取得
N, M = list(map(int, input().split()))

# 求解処理
result = int(N * (N - 1) / 2 + M * (M - 1) / 2)

# 結果出力
print(result)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02729/Python/s222855902.py", line 3, in <module>
    from scipy.special import comb
ModuleNotFoundError: No module named 'scipy'


n = int(input())
m = int(input())

sum = 0

if n > 1:
    sum += 2 ** (n // 2)
else:
    sum += 1

if m > 1:
    sum += 2 ** (m // 2)
else:
    sum += 1

print(sum)

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

count = 0
if n > 1:
    count += n * (n - 1) // 2
if m > 1:
    count += m * (m - 1) // 2
print(count)

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


import math

def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def main():
    n, m = map(int, input().split())
    print(combinations_count(n, 2) + combinations_count(m, 2))

if __name__ == "__main__":
    main()

import math

def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def main():
    n, m = map(int, input().split())
    if n < 2:
        even = 0
    else:
        even = combinations_count(n, 2)
    if m < 2:
        odd = 0
    else:
        odd = combinations_count(m, 2)
    print(even + odd)

if __name__ == "__main__":
    main()

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02729/Python/s584253829.py", line 14, in <module>
    main()
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02729/Python/s584253829.py", line 10, in main
    print(combinations_count(n, 2) + combinations_count(m, 2))
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02729/Python/s584253829.py", line 5, in combinations_count
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
ValueError: factorial() not defined for negative values


while True:
    m, n = list(map(int, input().split()))
    print(m * (m - 1) / 2 + n * (n - 1) / 2)

m, n = list(map(int, input().split()))
print(int(m * (m - 1) / 2 + n * (n - 1) / 2))

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


f = int(input()) / 3.0
print("{.9f}".format(f * f * f))

f = int(input()) / 3.0
print("{:.9f}".format(f * f * f))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02731/Python/s178614375.py", line 2, in <module>
    print("{.9f}".format(f * f * f))
AttributeError: 'float' object has no attribute '9f'


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

u = list(set(A))
c = []
sum = 0
for j in u:
    _ = A.count(j)
    c.append(_)
    sum += int(_ * (_ - 1) / 2)

s = ""
for k in A:
    v = c[u.index(k)]
    s += str(sum - v + 1) + "\\n"
print(s)

import collections

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

u = collections.Counter(A)
sum = 0
for j, c in u.items():
    sum += int(c * (c - 1) / 2)

s = ""
for k in A:
    s += str(sum - u[k] + 1) + "\\n"
print(s)


N = int(input())
line = list(map(int, input().split()))
dic = set(line)
nums = 0
for i in dic:
    cnt = line.count(i) - 1
    nums += (cnt * (cnt + 1)) // 2

for i in line:
    cnt = line.count(i) - 1
    print(nums - cnt)

from collections import Counter
import time

N = int(input())
line = list(map(int, input().split()))
dic = Counter(line)
nums = 0
for num, cnt in dic.items():
    if cnt > 1:
        nums += (cnt * (cnt - 1)) // 2
for i in line:
    print(nums - (dic[i] - 1))


N = int(input())
A = list(map(int, input().split()))
dictA = {}
for x in A:
    dictA[x] = 0
for x1 in A:
    dictA[x1] += 1

for x2 in A:
    dictB = dictA.copy()
    combisum = 0
    dictB[x2] -= 1
    for x3 in dictB.values():
        combisum += x3 * (x3 - 1) // 2
    print(combisum)

N = int(input())
A = list(map(int, input().split()))
dictA = {}
for x in A:
    dictA[x] = 0
for x1 in A:
    dictA[x1] += 1

combisum = 0
for y in dictA.values():
    combisum += y * (y - 1) // 2

for z in range(N):
    print(combisum - dictA[A[z]] + 1)


import collections

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

c = collections.Counter(A)

sum = 0

for a in A:
    for key in c.keys():
        if key == a:
            value_k = c[key] - 1
            sum += value_k * (value_k - 1) // 2
        else:
            value_k = c[key]
            sum += value_k * (value_k - 1) // 2
    print(sum)
    sum = 0

import collections

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

c = collections.Counter(A)

sum_dict = {}
sum_dict_n = {}

sum = 0
sum_n = 0

for key in c.keys():
    coll = c[key] * (c[key] - 1) // 2
    sum_dict[key] = coll
    sum += coll
    value_k = c[key] - 1
    coll_n = value_k * (value_k - 1) // 2
    sum_dict_n[key] = coll_n

for a in A:
    ans = sum
    ans = ans - sum_dict[a] + sum_dict_n[a]
    print(ans)


from scipy.misc import comb

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

print(int(comb(N, 2) + comb(M, 2)))

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

def comb2(n):
    return n * (n - 1) // 2

counts = [0] * (N + 1)
for a in A:
    counts[a] += 1
total = sum(map(lambda n: comb2(n), filter(lambda n: n > 1, counts)))

for a in A:
    print(total - (counts[a] - 1))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02732/Python/s178651076.py", line 1, in <module>
    from scipy.misc import comb
ModuleNotFoundError: No module named 'scipy'


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

counts = {}
for i in range(N):
    a = A[i]
    if a in counts:
        counts[a] += 1
        continue
    counts[a] = 1

# print(counts)

ans_memory = {}
for k in range(N):
    if A[k] in ans_memory:
        print(ans_memory[A[k]])
        continue

    counts_tmp = counts.copy()
    counts_tmp[A[k]] -= 1

    # print(counts_tmp)
    ans = 0
    for v in counts_tmp.values():
        ans += v * (v - 1) // 2
    ans_memory[A[k]] = ans
    print(ans)

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

counts = {}
for i in range(N):
    a = A[i]
    if a in counts:
        counts[a] += 1
    else:
        counts[a] = 1

# print(counts)

ans_memory = {}
ans_memory_val = {}
for k in range(N):
    if A[k] in ans_memory:
        print(ans_memory[A[k]])
        continue
    if counts[A[k]] in ans_memory_val:
        print(ans_memory_val[counts[A[k]]])
        continue

    counts_tmp = counts.copy()
    counts_tmp[A[k]] -= 1

    # print(counts_tmp)
    ans = 0
    for v in counts_tmp.values():
        ans += v * (v - 1) // 2
    ans_memory[A[k]] = ans
    ans_memory_val[counts[A[k]]] = ans
    print(ans)


def main():
    n = int(input())
    a_list = list(map(int, input().split()))

    a_dict = {}
    for a in a_list:
        if a not in a_dict:
            a_dict[a] = 1
        else:
            a_dict[a] += 1

    for k in range(n):
        cnt = 0
        a_dict[a_list[k]] -= 1
        for v in a_dict.values():
            if v >= 2:
                cnt += v * (v - 1) // 2
        a_dict[a_list[k]] += 1
        print(cnt)

if __name__ == "__main__":
    main()

def main():
    n = int(input())
    a_list = list(map(int, input().split()))
    num_list = [0] * n  # 各番号が書かれたボールが何個あるか
    method_list = [0] * n  # 同じ番号が書かれた異なる2つのボールを選ぶ方法

    for a in a_list:
        num_list[a - 1] += 1

    for i in range(n):
        b = num_list[i]
        if b >= 2:
            method_list[i] = b * (b - 1) // 2

    total_method = sum(method_list)

    for k in range(n):
        c = a_list[k]  # k番目のボールに書かれている数字
        ans = total_method - method_list[c - 1]
        d = num_list[c - 1]
        if d >= 3:
            e = (d - 1) * (d - 2) // 2
        else:
            e = 0
        ans += e
        print(ans)

if __name__ == "__main__":
    main()


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

count = {}
for x in A:
    if count.get(x):
        count[x] += 1
    else:
        count[x] = 1

for i in range(N):
    count[A[i]] -= 1
    s = 0
    for x in count.values():
        s += x * (x - 1) // 2
    print(s)
    count[A[i]] += 1

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

count = {}
for x in A:
    if count.get(x):
        count[x] += 1
    else:
        count[x] = 1

sub = {}
s = 0
for i, x in count.items():
    count[i] = x * (x - 1) // 2
    s += count[i]
    sub[i] = (x - 1) * (x - 2) // 2

for i in range(N):
    print(s - count[A[i]] + sub[A[i]])


import math

def comb(n, r):
    if n < r:
        return 0
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

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

d = {}
for a in A:
    if a in d:
        d[a] += 1
    else:
        d[a] = 1

d2 = {}
for k in range(N):
    a = A[k]

    if a not in d2:
        d2[a] = 0
        for i, n in d.items():
            if a == i:
                d2[a] += comb(n - 1, 2)
            else:
                d2[a] += comb(n, 2)
    print(d2[a])

import math

def comb(n, r):
    if n < r:
        return 0
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

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

d = {}
for a in A:
    if a in d:
        d[a] += 1
    else:
        d[a] = 1

b = 0
for n in d.values():
    b += comb(n, 2)

for k in range(N):
    a = A[k]
    print(b - d[a] + 1)


n = int(input())
dA = {}
A = []
for a in input().split():
    A.append(a)
    if a in dA:
        dA[a] += 1
    else:
        dA[a] = 1

cA = {}
for a in dA:
    cA[a] = dA[a] * (dA[a] - 1) // 2

for a in A:
    print(sum(cA.values()) - dA[a] + 1)

n = int(input())
dA = {}
A = []
for a in input().split():
    A.append(a)
    if a in dA:
        dA[a] += 1
    else:
        dA[a] = 1

cA = {}
for a in dA:
    cA[a] = dA[a] * (dA[a] - 1) // 2

s = sum(cA.values())
for a in A:
    print(s - dA[a] + 1)


# from collections import deque
from collections import Counter
from scipy.misc import comb
from copy import deepcopy

n = int(input())
a = list(map(int, input().split()))
cnt_n = 0
a_n = deepcopy(a)
c = Counter(a_n)
for key in c:
    cnt_n += comb(c[key], 2, exact=True)

for k in range(len(a)):
    a_n = deepcopy(a)
    a_k = deepcopy(a[k])
    a_n.pop(k)
    cnt_k = a_n.count(a_k)
    print(cnt_n - cnt_k)

# from collections import deque
from collections import Counter
from scipy.misc import comb

# from copy import deepcopy

n = int(input())
a = list(map(int, input().split()))
C = Counter(a)
S = 0
for key in C:
    S += comb(C[key], 2, exact=True)

for k in range(n):
    A = a[k]
    print(S - C[A] + 1)


from scipy.misc import comb
from sys import stdin

N = int(stdin.readline())
count1 = [0] * (N + 1)
count2 = [0] * (N + 1)
A = list(map(int, stdin.readline().split()))

B = list(set(A))

for b in B:
    num_of_b = A.count(b)
    if num_of_b > 2:
        count1[b] = comb(num_of_b, 2, exact=True)
        count2[b] = comb(num_of_b - 1, 2, exact=True)
    elif num_of_b == 2:
        count1[b] = 1

for a in A:
    ans = 0
    ans += sum(count1) - count1[a]
    ans += count2[a]
    print(ans)

from sys import stdin

N = int(stdin.readline())
a_dict = {}
A = list(map(int, stdin.readline().split()))
for a in A:
    if a in a_dict:
        a_dict[a] += 1
    else:
        a_dict[a] = 1

sum_comb = 0
B = set(A)
for b in B:
    n = a_dict[b]
    sum_comb += n * (n - 1) // 2

for a in A:
    ans = sum_comb
    n = a_dict[a]
    ans -= n * (n - 1) // 2
    ans += (n - 1) * (n - 2) // 2
    print(ans)


n = int(input())
numlist = list(map(int, input().split(" ")))
ans = []

sum = 0
for i in range(1, n + 1):
    tmp = numlist.count(i)
    sum += int(tmp * (tmp - 1) / 2)

for i in numlist:
    print(sum - numlist.count(i) + 1)

n = int(input())
numlist = list(map(int, input().split(" ")))

import collections

numcount = collections.Counter(numlist)

sum = 0
for i in numcount.values():
    sum += int(i * (i - 1) / 2)

for i in numlist:
    print(sum - numcount[i] + 1)


import math

def kumiawase(n):
    if n == 0 or n == 1:
        return 0
    return math.floor(math.factorial(n) / math.factorial(n - 2) / 2)

n = int(input())
aL = list(map(int, input().split(" ")))

d = {}

for a in aL:
    if a in d:
        d[a] += 1
    else:
        d[a] = 1

d2 = {}
d3 = {}

for dk, di in d.items():
    d2[dk] = kumiawase(di)
    d3[dk] = kumiawase(di - 1)

for a in aL:
    sm = sum(d2.values())
    print(sm - d2[a] + d3[a])

import math
import collections

def kumiawase(n):
    if n == 0 or n == 1:
        return 0
    return (n**2 - n) // 2

n = int(input())
aL = list(map(int, input().split(" ")))

d = collections.Counter(aL)

s = 0
for i in d.values():
    s += kumiawase(i)

for a in aL:
    print(s - d[a] + 1)


N = int(input())
A = [int(a) for a in input().split()]
cnt = {}
total = 0

for a in A:
    if a not in cnt:
        cnt[a] = 0
    cnt[a] += 1

for i in cnt.values():
    total += i * (i - 1) // 2

for i in range(N):
    print(total - (cnt[i] - 1))

N = int(input())
A = [int(a) for a in input().split()]
cnt = {}
total = 0

for a in A:
    if a not in cnt:
        cnt[a] = 0
    cnt[a] += 1

for i in cnt.values():
    total += i * (i - 1) // 2

for a in A:
    print(total - (cnt[a] - 1))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02732/Python/s071344434.py", line 15, in <module>
    print(total - (cnt[i] - 1))
KeyError: 0


import collections

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

C = collections.Counter(A)

for a in A:
    s = 0
    for c in C:
        if c == a:
            s += (C[c] - 1) * (C[c] - 2) // 2
        else:
            s += C[c] * (C[c] - 1) // 2
    print(s)

import collections

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

C = collections.Counter(A)

s_all = 0
for c in C:
    s_all += C[c] * (C[c] - 1) // 2

for a in A:
    s = 0
    s += s_all - (C[a] - 1)
    print(s)


n = int(input())
book = {}
array = [int(i) for i in input().split()]

for i in array:
    book[i] = book.get(i, 0) + 1

for i in range(n):
    s = 0
    for k, v in book.items():
        if k == array[i]:
            v -= 1
        s += (v * (v - 1)) // 2 if v > 0 else 0
    print(s)

n = int(input())
book = {}
array = [int(i) for i in input().split()]

for i in array:
    book[i] = book.get(i, 0) + 1

sum_val = 0
delta = {}
for k, v in book.items():
    t = (v * (v - 1)) // 2 if v > 0 else 0
    sum_val += t
    u = v - 1
    delta[k] = t - (u * (u - 1)) // 2 if u > 0 else 0

for i in range(n):
    print(sum_val - delta[array[i]])


from collections import Counter

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

# nC2 = [0] * (N + 1)
# nC2[0] = 0
# nC2[1] = 0
# for i in range(2, N + 1):
#     nC2[i] = i * (i - 1) // 2

# print(nC2)

def comb(x):
    if x == 0:
        return 0
    if x == 1:
        return 0
    return x * (x - 1) // 2

d = Counter(A)
# print(d)
k = d.keys()

# print(k)

for a in A:
    res = 0
    for kk in k:
        if a == kk:
            res += comb(d[kk] - 1)
            # res += nC2[d[kk] - 1]
        else:
            res += comb(d[kk])
            # res += nC2[d[kk]]
    # print(a, d[a], res)
    print(res)

from collections import Counter

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

def comb(x):
    if x == 0:
        return 0
    if x == 1:
        return 0
    return x * (x - 1) // 2

d = Counter(A)
# print(d)
k = d.keys()

# print(k)
total = 0

for kk in k:
    total += comb(d[kk])

# print(total)

for a in A:
    res = total
    res -= comb(d[a])
    res += comb(d[a] - 1)
    print(res)


N = int(input())
data = [i for i in input().split()]

number_count = {}
for cmp in data:
    if cmp in number_count:
        number_count[cmp] += 1
        continue
    number_count[cmp] = 1

answer = {}
for i in range(N):
    if data[i] in answer:
        print(answer[data[i]])
        continue
    C = 0
    number_count_temp = number_count.copy()
    number_count_temp[str(data[i])] -= 1
    for cmp in number_count_temp:
        C += int(number_count_temp[cmp] * (number_count_temp[cmp] - 1) / 2)

    print(str(C))
    answer[data[i]] = str(C)

N = int(input())
data = [i for i in input().split()]

number_count = {}
for cmp in data:
    if cmp in number_count:
        number_count[cmp] += 1
        continue
    number_count[cmp] = 1

C_tot = 0
for cmp in number_count:
    C_tot += int(number_count[cmp] * (number_count[cmp] - 1) / 2)

for k in range(N):
    C = (
        C_tot
        - int(number_count[data[k]] * (number_count[data[k]] - 1) / 2)
        + int((number_count[data[k]] - 1) * (number_count[data[k]] - 2) / 2)
    )
    print(str(C))


from collections import defaultdict
import math

N = int(input())
A = list(map(int, input().split()))
d = defaultdict(lambda: 0)
for i in range(len(A)):
    d[A[i]] += 1

r = 2
total = 0
calc_dict = {}
for k, v in zip(d.keys(), d.values()):
    if v > 1:
        ans1 = math.factorial(v) // (math.factorial(v - r) * math.factorial(r))
    else:
        ans1 = 0
    if v > 2:
        ans2 = math.factorial(v - 1) // (math.factorial(v - 1 - r) * math.factorial(r))
    else:
        ans2 = 0
    total += ans1
    calc_dict[k] = ans1 - ans2
for i in range(N):
    print(total - calc_dict[A[i]])

from collections import defaultdict

N = int(input())
A = list(map(int, input().split()))
d = defaultdict(lambda: 0)
for i in range(len(A)):
    d[A[i]] += 1
total = 0
for k, v in d.items():
    total += v * (v - 1) // 2
for a in A:
    print(total - (d[a] - 1))


from collections import Counter
from math import factorial

def perm(n, r):
    return factorial(n) // factorial(n - r)

def comb(n, r):
    if n < r:
        return 0
    return perm(n, r) // factorial(r)

N = int(input())
A = list(map(int, input().split()))
C = Counter(A)
D = {k: comb(v, 2) for k, v in C.items()}
_all = sum(D.values())
for a in A:
    print(_all - D[a] + comb(C[a] - 1, 2))

from collections import Counter

N = int(input())
A = list(map(int, input().split()))
C = Counter(A)
combinations = [0] + [c * (c - 1) // 2 for c in range(1, 1 + max(C.values()))]
_all = sum([combinations[c] for c in C.values()])
for a in A:
    print(_all - combinations[C[a]] + combinations[C[a] - 1])


import collections as cl
import math

def combinations_count(n, r):
    if n < r:
        return 0
    else:
        return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

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

cnt = cl.Counter(A)
ans = 0
mem = {}

for a in A:
    if a in mem:
        print(mem[a])
        continue
    ans = 0
    cnt[a] -= 1
    for v in cnt.values():
        if v < 2:
            continue
        ans += combinations_count(v, 2)
    cnt[a] += 1
    print(ans)
    mem[a] = ans

import collections as cl
import math

def combinations_count(n, r):
    if n < r:
        return 0
    else:
        return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

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

cnt = cl.Counter(A)
ans = 0
for v in cnt.values():
    ans += combinations_count(v, 2)

for a in A:
    print(ans - cnt[a] + 1)


from collections import Counter

N = int(input())
lst = [int(x) for x in input().split()]
counters = Counter(lst)
dic = {}
for k, v in dict(counters).items():
    if v > 1:
        dic[k] = v

m = {}
for x in lst:
    n = m.get(x)
    if n is None:
        n = 0
        for k, v in dic.items():
            if k == x:
                v -= 1
            n += v * (v - 1) // 2

    m[x] = n
    print(n)

from collections import Counter

N = int(input())
lst = [int(x) for x in input().split()]
dic = dict(Counter(lst))

ret = 0
for k, v in dic.items():
    ret += v * (v - 1) // 2

for x in lst:
    n = dic[x]
    if n == 1:
        print(ret)
    else:
        print(ret - (n * (n - 1) // 2) + ((n - 1) * (n - 2) // 2))


from itertools import combinations, chain

H, W, K = map(int, input().split())
Sss = []
for _ in range(H):
    Sss.append(list(map(int, input())))

def h_divide(Sss, div_is):
    result = []
    for s, e in zip(chain([0], div_is), chain(div_is, [len(Sss)])):
        result.append(Sss[s:e])
    return result

def _v_end(Sss, start, K):
    count = 0
    for i in range(start, len(Sss[0])):
        s = sum(map(lambda Ss: Ss[i], Sss))
        if count + s > K:
            return i - 1
        count += s
    return len(Sss[0]) - 1

def v_end(Ssss, start, K):
    result = -1
    for Sss in Ssss:
        end = _v_end(Sss, start, K)
        if end < start:
            return -1
        if result < 0 or result > end:
            result = end
    return result

def v_div_count(Ssss, K):
    start, result = 0, 0
    while True:
        end = v_end(Ssss, start, K)
        if end < 0:
            return -1
        if end == len(Ssss[0][0]) - 1:
            break
        result += 1
        start = end + 1
    return result

h_cands = list(range(1, len(Sss)))
ans = -1
for n in range(len(h_cands) + 1):
    for comb in combinations(h_cands, n):
        Ssss = h_divide(Sss, list(comb))
        cnt = v_div_count(Ssss, K)
        if cnt < 0:
            continue
        if ans < 0 or ans > n + cnt:
            ans = n + cnt
print(ans)

from itertools import combinations, chain

H, W, K = map(int, input().split())
Sss = []
for _ in range(H):
    Sss.append(list(map(int, input())))

def h_divide(Sss, div_is):
    result = []
    for s, e in zip(chain([0], div_is), chain(div_is, [len(Sss)])):
        result.append(Sss[s:e])
    return result

def _v_end(Sss, start, K):
    count = 0
    for i in range(start, len(Sss[0])):
        s = sum(map(lambda Ss: Ss[i], Sss))
        if count + s > K:
            return i - 1
        count += s
    return len(Sss[0]) - 1

def v_end(Ssss, start, K):
    result = -1
    for Sss in Ssss:
        end = _v_end(Sss, start, K)
        if end < start:
            return -1
        if result < 0 or result > end:
            result = end
    return result

def v_div_count(Ssss, K):
    start, result = 0, 0
    while True:
        end = v_end(Ssss, start, K)
        if end < 0:
            return -1
        if end == len(Ssss[0][0]) - 1:
            break
        result += 1
        start = end + 1
    return result

h_cands = list(range(1, len(Sss)))
ans = -1
for n in range(len(h_cands) + 1):
    for comb in combinations(h_cands, n):
        if ans > 0 and n >= ans:
            continue
        Ssss = h_divide(Sss, list(comb))
        cnt = v_div_count(Ssss, K)
        if cnt < 0:
            continue
        if ans < 0 or ans > n + cnt:
            ans = n + cnt
print(ans)


import itertools
import numpy as np
from sys import stdin

H, W, K = map(int, stdin.readline().split())
A = np.int32([[int(x) for x in stdin.readline().strip()] for _ in range(H)])

ans = H * W
for mask in itertools.product([0, 1], repeat=H - 1):
    pivots = [r + 1 for r in range(H - 1) if mask[r]]
    if len(pivots) > ans:
        continue

    blocks = np.concatenate([block.sum(axis=0) for block in np.split(A, pivots)])
    blocks = blocks.reshape(len(pivots) + 1, W)
    if blocks.max() > K:
        continue

    n_block = blocks.shape[0]
    n_cut = n_block - 1
    sums = np.zeros(n_block, dtype=int)

    for c in range(W):
        adds = blocks[:, c]
        sums = sums + adds
        if np.any(sums > K):
            n_cut += 1
            sums = adds
            if n_cut >= ans:
                break

    ans = min(ans, n_cut)

print(ans)

import itertools

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

def solve(blocks):
    n_block = len(blocks)
    n_cut = n_block - 1
    sums = [0 for _ in range(n_block)]

    for c in range(W):
        adds = [block[c] for block in blocks]
        if any(a > K for a in adds):
            return H * W

        sums = [s + a for s, a in zip(sums, adds)]
        if any(s > K for s in sums):
            n_cut += 1
            sums = adds

    return n_cut

ans = H * W
for mask in itertools.product([0, 1], repeat=H - 1):
    mask = [1] + list(mask) + [1]
    pivots = [r for r in range(H + 1) if mask[r]]
    blocks = [A[p1:p2] for p1, p2 in zip(pivots[:-1], pivots[1:])]
    blocks = [[sum(row[c] for row in block) for c in range(W)] for block in blocks]
    ans = min(ans, solve(blocks))
print(ans)


import sys

input = sys.stdin.buffer.readline
n, s = map(int, input().split())
A = list(map(int, input().split()))
dp = [[0] * (s + 1) for _ in range(n + 1)]

mod = 998244353
# dp[i][s] A[i]まで見た時、合計sになる数。
# 各々の地点で新しく開始されるものも有るので毎回dp[i][0]は＋1
dp[0][0] = 1
ans = 0
for i in range(n):
    ni = i + 1
    for j in range(s + 1):
        nj = j
        dp[ni][nj] += dp[i][j]
        dp[ni][nj] %= mod
        nj = j + A[i]
        if nj <= s:
            dp[ni][nj] += dp[i][j]
            dp[ni][nj] %= mod
    dp[ni][0] += 1
    ans += dp[ni][s]
    ans %= mod
print(ans)

n, s = map(int, input().split())
A = list(map(int, input().split()))
mod = 998244353
dp = [[0] * (s + 1) for _ in range(n + 1)]
for i in range(n):
    dp[i][0] = 1
for i in range(n):
    ni = i + 1
    for j in range(s + 1):
        nj = j
        dp[ni][nj] += dp[i][j]
        dp[ni][nj] %= mod
        nj = j + A[i]
        if nj <= s:
            dp[ni][nj] += dp[i][j]
            dp[ni][nj] %= mod
ans = 0
for i in range(n + 1):
    ans += dp[i][s]
    ans %= mod
print(ans)


n, s = map(int, input().split())
a = tuple(map(int, input().split()))
MOD = 998244353

# dp = [[0] * (s + 1) for _ in range(n + 1)]
# dp[0][0] = 1
# for i in range(n):  # ここをrange(i, n)にすると、f(i, r)の計算ができる
#     for j in range(s + 1):
#         dp[i + 1][j] += dp[i][j]  # do NOT use a[i]
#         if j + a[i] <= s:
#             dp[i + 1][j + a[i]] += dp[i][j]  # USE a[i]
# # f(1, n) = dp[n][s]
# # f(1, i) = dp[i][s] (i = 1, 2, ..., n)
# print('dp')
# print(*dp, sep='\\n')

dp0 = [[0] * (s + 1) for _ in range(n + 1)]
dp1 = [[0] * (s + 1) for _ in range(n + 1)]
dp0[0][0] = 1
ans = 0
for i in range(n):
    for j in range(s + 1):
        # i番目の要素は使わない
        dp0[i + 1][j] += dp0[i][j]
        dp0[i + 1][j] %= MOD
        dp1[i + 1][j] += dp0[i][j] + dp1[i][j]
        dp1[i + 1][j] %= MOD

        if j + a[i] <= s:
            dp1[i + 1][j + a[i]] += dp0[i][j] + dp1[i][j]
            dp1[i + 1][j + a[i]] %= MOD

    ans += dp1[i + 1][s]
    ans %= MOD
# dp[r][s][1] = \\sum_{i=1}^{r} f(i, r)

# print('dp[][][1]')
# for i in range(n + 1):
#     print([dp[i][j][1] for j in range(s + 1)])

print(ans)


import numpy as np

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

fwd_acc = np.zeros((n + 1, s + 1), dtype=np.int64)
fwd_acc[0][0] = 1

ans = 0
MOD = 998244353
for i, a in enumerate(aaa, start=1):
    fwd_acc[i] = fwd_acc[i - 1]
    fwd_acc[i][0] = i
    if a <= s:
        fwd_acc[i][a:] += fwd_acc[i][:-a]
    ans = (ans + fwd_acc[i - 1][s - a] * (n - i + 1)) % MOD
print(ans)

import numpy as np

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

fwd_acc = np.zeros((n + 1, s + 1), dtype=np.int64)
fwd_acc[0][0] = 1

ans = 0
MOD = 998244353
for i, a in enumerate(aaa, start=1):
    fwd_acc[i] = fwd_acc[i - 1]
    fwd_acc[i][0] = i
    if a <= s:
        fwd_acc[i][a:] = fwd_acc[i][a:] + fwd_acc[i][:-a]
    fwd_acc[i] %= MOD
    ans = (ans + fwd_acc[i][s]) % MOD
    # print(fwd_acc)
    # print(ans)
print(ans)


from copy import deepcopy

N, S = map(int, input().split())
A = [0] + list(map(int, input().split()))
mod = 998244353

dp = [0] * (S + 1)
dp2 = [0] * (S + 1)

"""
dp[i][j] = (i個までの数を使ってj点とる組み合わせ)
としたはいいが、f(L, R)をf(1,L)とf(1, R)に分解できずに爆死したのが敗因。

各(L, R)に対してdpするとTLEになるから手詰まりになると思ったわけだけど、
上のdpテーブルを各iに対して使い回しつつ、新たなdpテーブル[1, 0, 0, ...]を
作成して「元のdpテーブルに加算しておけば」dpテーブル一個で1番目スタート、2番目スタート、
..., L番目スタートのdpテーブル全てを考えられる！
（解説放送前半を参考）
"""

# i == 0の時
dp[0] = 1
ans = 0

# i >= 1の時
for i in range(1, N + 1):
    for j in range(S + 1):
        if j - A[i] < 0:
            dp2[j] = dp[j]
        else:
            dp2[j] = dp[j] + dp[j - A[i]]
    ans += dp2[S]
    ans %= mod

    dp = deepcopy(dp2)
    dp[0] += 1
    dp2 = [0] * (S + 1)

print(ans)

N, S = map(int, input().split())
A = [0] + list(map(int, input().split()))
mod = 998244353

dp = [0] * (S + 1)
dp2 = [0] * (S + 1)

"""
dp[i][j] = (i個までの数を使ってj点とる組み合わせ)
としたはいいが、f(L, R)をf(1,L)とf(1, R)に分解できずに爆死したのが敗因。

各(L, R)に対してdpするとTLEになるから手詰まりになると思ったわけだけど、
上のdpテーブルを各iに対して使い回しつつ、新たなdpテーブル[1, 0, 0, ...]を
作成して「元のdpテーブルに加算しておけば」dpテーブル一個で1番目スタート、2番目スタート、
..., L番目スタートのdpテーブル全てを考えられる！
（解説放送前半を参考）
"""

# i == 0の時
dp[0] = 1
ans = 0

# i >= 1の時
for i in range(1, N + 1):
    for j in range(S + 1):
        if j - A[i] < 0:
            dp2[j] = dp[j]
        else:
            dp2[j] = dp[j] + dp[j - A[i]]
    ans += dp2[S]
    ans %= mod

    dp = dp2  # deepcopyしなくてもこれで十分なはずだし、ポインタ渡しなので高速？
    dp[0] += 1
    dp2 = [0] * (S + 1)

print(ans)


import sys
from itertools import permutations

def input():
    return sys.stdin.readline().strip()

def main():
    H, W = map(int, input().split())

    S = [list(input()) for _ in range(H)]
    C = [2 * i for i in range(H - 1)] + [2 * j + 1 for j in range(W - 1)]
    check = list(permutations(C))
    answer = float("inf")
    for chk in check:
        if S[0][0] == "#":
            cnt = 1
        else:
            cnt = 0
        now = [0, 0]
        for i in range(H + W - 2):
            if chk[i] % 2 == 0:
                now[0] += 1
            else:
                now[1] += 1
            if now[0] <= H - 1 and now[1] <= W - 1:
                if S[now[0]][now[1]] == "#":
                    cnt += 1
            # print(now)
            # print(cnt)
        if cnt < answer:
            answer = cnt
    print(answer)

main()

import sys

def input():
    return sys.stdin.readline().strip()

def main():
    H, W = map(int, input().split())

    S = [list(input()) for _ in range(H)]
    # print(S)
    check = [[10**9 for i in range(W)] for j in range(H)]
    if S[0][0] == "#":
        check[0][0] = 1
    else:
        check[0][0] = 0
    for i in range(1, W):
        left = check[0][i - 1]
        if S[0][i] == "#":
            if S[0][i - 1] == "#":
                check[0][i] = left
            else:
                check[0][i] = left + 1
        else:
            check[0][i] = left
    for i in range(1, H):
        up = check[i - 1][0]
        if S[i][0] == "#":
            if S[i - 1][0] == "#":
                check[i][0] = up
            else:
                check[i][0] = up + 1
        else:
            check[i][0] = up
    for i in range(1, H):
        for j in range(1, W):
            # print(S[i][j])
            left = check[i][j - 1]
            up = check[i - 1][j]
            if S[i][j] == "#":
                if S[i][j - 1] == "#" and S[i - 1][j] == "#":
                    check[i][j] = min(left, up)
                elif S[i][j - 1] != "#" and S[i - 1][j] == "#":
                    check[i][j] = min(left + 1, up)
                elif S[i][j - 1] == "#" and S[i - 1][j] != "#":
                    check[i][j] = min(left, up + 1)
                else:
                    check[i][j] = min(left, up) + 1
            else:
                check[i][j] = min(left, up)
    # print(check)
    print(check[-1][-1])

main()


#!/usr/bin/env python3
from collections import deque

h, w = map(int, input().split())
maze = [[i == "#" for i in input()] for _ in range(h)]

dx = [1, 0]
dy = [0, 1]

que = deque([])
que.append((0, 0, maze[0][0], 1 if maze[0][0] else 0))
count = 10**5

while que:
    x, y, b, c = que.pop()
    if x == h - 1 and y == w - 1:
        count = min(count, c)
    elif c < count:
        for i in range(2):
            nx = x + dx[i]
            ny = y + dy[i]

            if not (0 <= nx < h and 0 <= ny < w):
                continue
            que.append((nx, ny, maze[nx][ny], c + (not b and maze[nx][ny])))
print(count)

#!/usr/bin/env python3
from collections import deque

h, w = map(int, input().split())
maze = [[i == "#" for i in input()] for _ in range(h)]

dx = [1, 0]
dy = [0, 1]

que = deque([])
que.append((0, 0, maze[0][0], 1 if maze[0][0] else 0))
count = [[h + w] * w for _ in range(h)]

while que:
    x, y, b, c = que.pop()
    if c >= count[x][y]:
        continue
    count[x][y] = c
    if x == h - 1 and y == w - 1:
        continue
    for i in range(2):
        nx = x + dx[i]
        ny = y + dy[i]

        if not (0 <= nx < h and 0 <= ny < w):
            continue
        que.append((nx, ny, maze[nx][ny], c + (not b and maze[nx][ny])))
print(count[h - 1][w - 1])


import math

firstInputText = input()
inputList = firstInputText.split()
a = int(inputList[0])
b = int(inputList[1])
c = int(inputList[2])
x = math.sqrt(a) + math.sqrt(b)
y = math.sqrt(c)
# print(x)
# print(y)

# if math.isclose(x,y):
#     print("Yes")
# else:
#     print("No")
if x == y:
    print("No")
elif x < y:
    print("Yes")
else:
    print("No")

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02741/Python/s436801336.py", line 6, in <module>
    b = int(inputList[1])
IndexError: list index out of range


H, W = map(int, input().split())

if H == 1 or W == 1:
    print(1)
else:
    if (H * W) % 2 == 1:
        ans = H * W // 2 + 1
    else:
        ans = H * W // 2
print(ans)


import math

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

if h == 1 or w == 1:
    print(1)
elif (h * w) % 2 == 0:
    ans = (h * w) // 2
else:
    ans = (h // 2) * w + math.ceil(w / 2)

print(ans)

import math

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

if h == 1 or w == 1:
    ans = 1
elif (h * w) % 2 == 0:
    ans = (h * w) // 2
else:
    ans = (h // 2) * w + math.ceil(w / 2)

print(ans)


from math import sqrt, isclose

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

if isclose(sqrt(c) - (sqrt(a) + sqrt(b)), 0):
    print("Yes")
else:
    print("No")

from math import sqrt
from decimal import Decimal, getcontext

a, b, c = map(int, input().split())
if c - a - b > 0 and (c - a - b) ** 2 > 4 * a * b:
    print("Yes")
else:
    print("No")


from decimal import Decimal

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

A = Decimal(a) ** (1 / 2) + Decimal(b) ** (1 / 2)
C = Decimal(c) ** (1 / 2)
if A < C:
    print("Yes")
else:
    print("No")

from decimal import Decimal

a, b, c = map(int, input().split())
k = Decimal(0.5)

A = Decimal(a) ** k + Decimal(b) ** k
C = Decimal(c) ** k
if A < C:
    print("Yes")
else:
    print("No")

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02743/Python/s242676501.py", line 6, in <module>
    A = Decimal(a) ** (1 / 2) + Decimal(b) ** (1 / 2)
TypeError: unsupported operand type(s) for ** or pow(): 'decimal.Decimal' and 'float'


a, b, c = input().split()

if c - a - b > 0:
    if 4 * a * b < (c - a - b) ** 2:
        print("Yes")
    else:
        print("No")
else:
    print("No")

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

if c - a - b > 0:
    if 4 * a * b < (c - a - b) ** 2:
        print("Yes")
    else:
        print("No")
else:
    print("No")

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02743/Python/s899697147.py", line 3, in <module>
    if c - a - b > 0:
TypeError: unsupported operand type(s) for -: 'str' and 'str'


N = int(input())
A = {
    1: ["a"],
    2: ["aa", "ab"],
    3: ["aaa", "aab", "aba", "abb", "abc"],
    4: [
        "aaaa",
        "aaab",
        "aabb",
        "aabc",
        "abaa",
        "abab",
        "abac",
        "abba",
        "abbb",
        "abbc",
        "abca",
        "abcb",
        "abcc",
        "abcd",
    ],
    5: [
        "aaaaa",
        "aaaab",
        "aaaba",
        "aaabb",
        "aaabc",
        "aabba",
        "aabbb",
        "aabbc",
        "aabca",
        "aabcb",
        "aabcc",
        "aabcd",
        "abaaa",
        "abaab",
        "abaac",
        "ababa",
        "ababb",
        "ababc",
        "abaca",
        "abacb",
        "abacc",
        "abacd",
        "abbaa",
        "abbab",
        "abbac",
        "abbba",
        "abbbb",
        "abbbc",
        "abbca",
        "abbcb",
        "abbcc",
        "abbcd",
        "abcaa",
        "abcab",
        "abcac",
        "abcad",
        "abcba",
        "abcbb",
        "abcbc",
        "abcbd",
        "abcca",
        "abccb",
        "abccc",
        "abccd",
        "abcda",
        "abcdb",
        "abcdc",
        "abcdd",
        "abcde",
    ],
}
Ans = A[N]
for i in range(len(Ans)):
    print(Ans[i])

N = int(input())
D = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
Ans = [["a"]]
for i in range(1, 10):
    before = Ans[i - 1]
    # print(before)
    next = []
    for j in before:
        L = set(list(j))
        # print(L)
        for k in range(len(L) + 1):
            # print(j)
            next.append(j + D[k])
    Ans.append(next)
# print(Ans)
print(*Ans[N - 1], sep="\\n")


"""
検証: https://twitter.com/neterukun_cd/status/1283020759942619139
"""

def main():
    MAX_N = 2000
    a = [ord(char) for char in input()]
    b = [ord(char) for char in input()]
    c = [ord(char) for char in input()]

    len_a = len(a)
    len_b = len(b)
    len_c = len(c)

    a += [63] * (MAX_N - len_a + 10)
    b += [63] * (MAX_N - len_b + 10)
    c += [63] * (MAX_N - len_c + 10)

    ab = [True] * (2 * MAX_N + 10)
    ba = [True] * (2 * MAX_N + 10)
    bc = [True] * (2 * MAX_N + 10)
    cb = [True] * (2 * MAX_N + 10)
    ca = [True] * (2 * MAX_N + 10)
    ac = [True] * (2 * MAX_N + 10)

    for length in range(MAX_N + 1):
        for i in range(MAX_N + 1):
            if i + length > MAX_N:
                break

            if a[i + length] != b[i] and a[i + length] != 63 and b[i] != 63:
                ab[length] = False
            if b[i + length] != a[i] and b[i + length] != 63 and a[i] != 63:
                ba[length] = False

            if b[i + length] != c[i] and b[i + length] != 63 and c[i] != 63:
                bc[length] = False
            if c[i + length] != b[i] and c[i + length] != 63 and b[i] != 63:
                cb[length] = False

            if c[i + length] != a[i] and c[i + length] != 63 and a[i] != 63:
                ca[length] = False
            if a[i + length] != c[i] and a[i + length] != 63 and c[i] != 63:
                ac[length] = False

    ans = MAX_N * 6
    """
    # AC
    for len1 in range(MAX_N + 1):
        for len2 in range(MAX_N + 1):
            if ab[len1] and bc[len2] and ac[len1 + len2]:
                tmp = max(len_a, len_b + len1, len_c + len1 + len2)
                ans = min(ans, tmp)
            if ba[len1] and ac[len2] and bc[len1 + len2]:
                tmp = max(len_b, len_a + len1, len_c + len1 + len2)
                ans = min(ans, tmp)

    for len1 in range(MAX_N + 1):
        for len2 in range(MAX_N + 1):
            if bc[len1] and ca[len2] and ba[len1 + len2]:
                tmp = max(len_b, len_c + len1, len_a + len1 + len2)
                ans = min(ans, tmp)
            if cb[len1] and ba[len2] and ca[len1 + len2]:
                tmp = max(len_c, len_b + len1, len_a + len1 + len2)
                ans = min(ans, tmp)

    for len1 in range(MAX_N + 1):
        for len2 in range(MAX_N + 1):
            if ca[len1] and ab[len2] and cb[len1 + len2]:
                tmp = max(len_c, len_a + len1, len_b + len1 + len2)
                ans = min(ans, tmp)
            if ac[len1] and cb[len2] and ab[len1 + len2]:
                tmp = max(len_a, len_c + len1, len_b + len1 + len2)
                ans = min(ans, tmp)
    """
    # TLE?
    for len1 in range(MAX_N + 1):
        for len2 in range(MAX_N + 1):
            if ab[len1] and bc[len2] and ac[len1 + len2]:
                tmp = max(len_a, len_b + len1, len_c + len1 + len2)
                ans = min(ans, tmp)
            if ba[len1] and ac[len2] and bc[len1 + len2]:
                tmp = max(len_b, len_a + len1, len_c + len1 + len2)
                ans = min(ans, tmp)

            if bc[len1] and ca[len2] and ba[len1 + len2]:
                tmp = max(len_b, len_c + len1, len_a + len1 + len2)
                ans = min(ans, tmp)
            if cb[len1] and ba[len2] and ca[len1 + len2]:
                tmp = max(len_c, len_b + len1, len_a + len1 + len2)
                ans = min(ans, tmp)

            if ca[len1] and ab[len2] and cb[len1 + len2]:
                tmp = max(len_c, len_a + len1, len_b + len1 + len2)
                ans = min(ans, tmp)
            if ac[len1] and cb[len2] and ab[len1 + len2]:
                tmp = max(len_a, len_c + len1, len_b + len1 + len2)
                ans = min(ans, tmp)

    print(ans)

if __name__ == "__main__":
    main()

"""
検証: https://twitter.com/neterukun_cd/status/1283020759942619139
"""
MAX_N = 2000
a = [ord(char) for char in input()]
b = [ord(char) for char in input()]
c = [ord(char) for char in input()]

len_a = len(a)
len_b = len(b)
len_c = len(c)

a += [63] * (MAX_N - len_a + 10)
b += [63] * (MAX_N - len_b + 10)
c += [63] * (MAX_N - len_c + 10)

ab = [True] * (2 * MAX_N + 10)
ba = [True] * (2 * MAX_N + 10)
bc = [True] * (2 * MAX_N + 10)
cb = [True] * (2 * MAX_N + 10)
ca = [True] * (2 * MAX_N + 10)
ac = [True] * (2 * MAX_N + 10)

for length in range(MAX_N + 1):
    for i in range(MAX_N + 1):
        if i + length > MAX_N:
            break

        if a[i + length] != b[i] and a[i + length] != 63 and b[i] != 63:
            ab[length] = False
        if b[i + length] != a[i] and b[i + length] != 63 and a[i] != 63:
            ba[length] = False

        if b[i + length] != c[i] and b[i + length] != 63 and c[i] != 63:
            bc[length] = False
        if c[i + length] != b[i] and c[i + length] != 63 and b[i] != 63:
            cb[length] = False

        if c[i + length] != a[i] and c[i + length] != 63 and a[i] != 63:
            ca[length] = False
        if a[i + length] != c[i] and a[i + length] != 63 and c[i] != 63:
            ac[length] = False

ans = MAX_N * 6
"""
# AC
for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if ab[len1] and bc[len2] and ac[len1 + len2]:
            tmp = max(len_a, len_b + len1, len_c + len1 + len2)
            ans = min(ans, tmp)
        if ba[len1] and ac[len2] and bc[len1 + len2]:
            tmp = max(len_b, len_a + len1, len_c + len1 + len2)
            ans = min(ans, tmp)

for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if bc[len1] and ca[len2] and ba[len1 + len2]:
            tmp = max(len_b, len_c + len1, len_a + len1 + len2)
            ans = min(ans, tmp)
        if cb[len1] and ba[len2] and ca[len1 + len2]:
            tmp = max(len_c, len_b + len1, len_a + len1 + len2)
            ans = min(ans, tmp)

for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if ca[len1] and ab[len2] and cb[len1 + len2]:
            tmp = max(len_c, len_a + len1, len_b + len1 + len2)
            ans = min(ans, tmp)
        if ac[len1] and cb[len2] and ab[len1 + len2]:
            tmp = max(len_a, len_c + len1, len_b + len1 + len2)
            ans = min(ans, tmp)
"""
# TLE?
for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if ab[len1] and bc[len2] and ac[len1 + len2]:
            tmp = max(len_a, len_b + len1, len_c + len1 + len2)
            ans = min(ans, tmp)
        if ba[len1] and ac[len2] and bc[len1 + len2]:
            tmp = max(len_b, len_a + len1, len_c + len1 + len2)
            ans = min(ans, tmp)

        if bc[len1] and ca[len2] and ba[len1 + len2]:
            tmp = max(len_b, len_c + len1, len_a + len1 + len2)
            ans = min(ans, tmp)
        if cb[len1] and ba[len2] and ca[len1 + len2]:
            tmp = max(len_c, len_b + len1, len_a + len1 + len2)
            ans = min(ans, tmp)

for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if ca[len1] and ab[len2] and cb[len1 + len2]:
            tmp = max(len_c, len_a + len1, len_b + len1 + len2)
            ans = min(ans, tmp)
        if ac[len1] and cb[len2] and ab[len1 + len2]:
            tmp = max(len_a, len_c + len1, len_b + len1 + len2)
            ans = min(ans, tmp)

print(ans)


"""
検証: https://twitter.com/neterukun_cd/status/1283020759942619139
"""
MAX_N = 2000
a = [ord(char) for char in input()]
b = [ord(char) for char in input()]
c = [ord(char) for char in input()]

len_a = len(a)
len_b = len(b)
len_c = len(c)

a += [63] * (MAX_N - len_a + 10)
b += [63] * (MAX_N - len_b + 10)
c += [63] * (MAX_N - len_c + 10)

ab = [True] * (2 * MAX_N + 10)
ba = [True] * (2 * MAX_N + 10)
bc = [True] * (2 * MAX_N + 10)
cb = [True] * (2 * MAX_N + 10)
ca = [True] * (2 * MAX_N + 10)
ac = [True] * (2 * MAX_N + 10)

for length in range(MAX_N + 1):
    for i in range(MAX_N + 1):
        if i + length > MAX_N:
            break

        if a[i + length] != b[i] and a[i + length] != 63 and b[i] != 63:
            ab[length] = False
        if b[i + length] != a[i] and b[i + length] != 63 and a[i] != 63:
            ba[length] = False

        if b[i + length] != c[i] and b[i + length] != 63 and c[i] != 63:
            bc[length] = False
        if c[i + length] != b[i] and c[i + length] != 63 and b[i] != 63:
            cb[length] = False

        if c[i + length] != a[i] and c[i + length] != 63 and a[i] != 63:
            ca[length] = False
        if a[i + length] != c[i] and a[i + length] != 63 and c[i] != 63:
            ac[length] = False

ans = MAX_N * 6
# TLE?
for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        length = len1 + len2
        if ab[len1] and bc[len2] and ac[length]:
            tmp = max(len_a, len_b + len1, len_c + length)
            ans = min(ans, tmp)
        if ba[len1] and ac[len2] and bc[length]:
            tmp = max(len_b, len_a + len1, len_c + length)
            ans = min(ans, tmp)
        if bc[len1] and ca[len2] and ba[length]:
            tmp = max(len_b, len_c + len1, len_a + length)
            ans = min(ans, tmp)
        if cb[len1] and ba[len2] and ca[length]:
            tmp = max(len_c, len_b + len1, len_a + length)
            ans = min(ans, tmp)
        if ca[len1] and ab[len2] and cb[length]:
            tmp = max(len_c, len_a + len1, len_b + length)
            ans = min(ans, tmp)
        if ac[len1] and cb[len2] and ab[length]:
            tmp = max(len_a, len_c + len1, len_b + length)
            ans = min(ans, tmp)

print(ans)

"""
検証: https://twitter.com/neterukun_cd/status/1283020759942619139
"""
MAX_N = 2000
a = [ord(char) for char in input()]
b = [ord(char) for char in input()]
c = [ord(char) for char in input()]

len_a = len(a)
len_b = len(b)
len_c = len(c)

a += [63] * (MAX_N - len_a + 10)
b += [63] * (MAX_N - len_b + 10)
c += [63] * (MAX_N - len_c + 10)

ab = [True] * (2 * MAX_N + 10)
ba = [True] * (2 * MAX_N + 10)
bc = [True] * (2 * MAX_N + 10)
cb = [True] * (2 * MAX_N + 10)
ca = [True] * (2 * MAX_N + 10)
ac = [True] * (2 * MAX_N + 10)

for length in range(MAX_N + 1):
    for i in range(MAX_N + 1):
        if i + length > MAX_N:
            break

        if a[i + length] != b[i] and a[i + length] != 63 and b[i] != 63:
            ab[length] = False
        if b[i + length] != a[i] and b[i + length] != 63 and a[i] != 63:
            ba[length] = False

        if b[i + length] != c[i] and b[i + length] != 63 and c[i] != 63:
            bc[length] = False
        if c[i + length] != b[i] and c[i + length] != 63 and b[i] != 63:
            cb[length] = False

        if c[i + length] != a[i] and c[i + length] != 63 and a[i] != 63:
            ca[length] = False
        if a[i + length] != c[i] and a[i + length] != 63 and c[i] != 63:
            ac[length] = False

ans = MAX_N * 6
"""
# AC
for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if ab[len1] and bc[len2] and ac[len1 + len2]:
            tmp = max(len_a, len_b + len1, len_c + len1 + len2)
            ans = min(ans, tmp)
        if ba[len1] and ac[len2] and bc[len1 + len2]:
            tmp = max(len_b, len_a + len1, len_c + len1 + len2)
            ans = min(ans, tmp)

for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if bc[len1] and ca[len2] and ba[len1 + len2]:
            tmp = max(len_b, len_c + len1, len_a + len1 + len2)
            ans = min(ans, tmp)
        if cb[len1] and ba[len2] and ca[len1 + len2]:
            tmp = max(len_c, len_b + len1, len_a + len1 + len2)
            ans = min(ans, tmp)

for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if ca[len1] and ab[len2] and cb[len1 + len2]:
            tmp = max(len_c, len_a + len1, len_b + len1 + len2)
            ans = min(ans, tmp)
        if ac[len1] and cb[len2] and ab[len1 + len2]:
            tmp = max(len_a, len_c + len1, len_b + len1 + len2)
            ans = min(ans, tmp)
"""
# TLE?
for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if ab[len1] and bc[len2] and ac[len1 + len2]:
            tmp = max(len_a, len_b + len1, len_c + len1 + len2)
            ans = min(ans, tmp)
for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if ba[len1] and ac[len2] and bc[len1 + len2]:
            tmp = max(len_b, len_a + len1, len_c + len1 + len2)
            ans = min(ans, tmp)
for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if bc[len1] and ca[len2] and ba[len1 + len2]:
            tmp = max(len_b, len_c + len1, len_a + len1 + len2)
            ans = min(ans, tmp)
for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if cb[len1] and ba[len2] and ca[len1 + len2]:
            tmp = max(len_c, len_b + len1, len_a + len1 + len2)
            ans = min(ans, tmp)
for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if ca[len1] and ab[len2] and cb[len1 + len2]:
            tmp = max(len_c, len_a + len1, len_b + len1 + len2)
            ans = min(ans, tmp)
for len1 in range(MAX_N + 1):
    for len2 in range(MAX_N + 1):
        if ac[len1] and cb[len2] and ab[len1 + len2]:
            tmp = max(len_a, len_c + len1, len_b + len1 + len2)
            ans = min(ans, tmp)

print(ans)


S = input()
ok = True
for i in range(0, len(S), 2):
    if not (S[i] == "h" and S[i + 1] == "i"):
        ok = False
        break
print("Yes" if ok else "No")

S = input()
ok = True
for i in range(0, len(S), 2):
    try:
        if not (S[i] == "h" and S[i + 1] == "i"):
            ok = False
            break
    except IndexError:
        ok = False
        break
print("Yes" if ok else "No")


A, B, M = map(int, input().split())
x, y, c = [0] * M, [0] * M, [0] * M
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(M):
    x[i], y[i], c[i] = map(int, input().split())
ans = 0
sav = 0
maxc = max(c)
ci = c.index(maxc)
disc = a[ci - 1] + b[ci - 1] - maxc
print(min(disc, min(a) + min(b)))

A, B, M = map(int, input().split())
x, y, c = [0] * M, [0] * M, [0] * M
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(M):
    x[i], y[i], c[i] = map(int, input().split())
ans, sav = float("inf"), 0
for j in range(M):
    sav = a[x[j] - 1] + b[y[j] - 1] - c[j]
    if ans > sav:
        ans = sav

print(min(ans, min(a) + min(b)))


a, b, m = map(int, input().split())
arr = list(map(int, input().split()))
brr = list(map(int, input().split()))
crr = [[0] * b for _ in range(a)]
xycs = [tuple(map(int, input().split())) for _ in range(m)]
ans = min(arr) + min(brr)

for elem in xycs:
    x = elem[0]
    y = elem[1]
    c = elem[2]
    ans = min(arr[x - 1] + arr[y - 1] - c, ans)

print(ans)

a, b, m = map(int, input().split())
arr = list(map(int, input().split()))
brr = list(map(int, input().split()))
xycs = [tuple(map(int, input().split())) for _ in range(m)]
ans = min(arr) + min(brr)

for elem in xycs:
    x = elem[0]
    y = elem[1]
    c = elem[2]
    ans = min((arr[x - 1] + brr[y - 1] - c), ans)

print(ans)


import numpy as np

A, B, M = map(int, input().split())
a = list(map(int, input().split()))
a = np.array(a)
b = list(map(int, input().split()))
b = np.array(b)
z = [list(map(int, input().split())) for _ in range(M)]
z = np.array(z)

xx, yy = np.meshgrid(a, b)
xx1 = xx.flatten()
yy1 = yy.flatten()

xxyy = np.c_[xx1, yy1]
mem = xxyy.sum(axis=1)
# mem = list(mem)
mem2 = []
for x, y, c in z:
    mem2.append(a[x - 1] + b[y - 1] - c)
np.append(mem, mem2)

print(min(mem))
# print(mem)

A, B, M = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
L = [[int(x) for x in input().split()] for _ in range(M)]

reg = min(a) + min(b)
for x, y, c in L:
    tmp = a[x - 1] + b[y - 1] - c
    reg = min(reg, tmp)
print(reg)


import sys

sys.setrecursionlimit(2 * 10**6)

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

def dfs(n, d):
    if depth[n] != -1:
        return
    depth[n] = d
    for nn in eAB[n]:
        dfs(nn, d + 1)
    return

N = int(input())
AB = [inpl() for i in range(N - 1)]

eAB = [[] for i in range(N)]
for a, b in AB:
    eAB[a - 1].append(b - 1)
    eAB[b - 1].append(a - 1)

depth = [-1 for i in range(N)]

dfs(0, 0)

eo = [[], []]
for i in range(N):
    eo[depth[i] % 2].append(i)

ans = [-1 for i in range(N)]
if len(eo[0]) > N // 3 and len(eo[1]) > N // 3:
    for i in range(N // 3):
        ans[3 * i] = eo[0][i]
        ans[3 * i + 1] = eo[1][i]
    t_0 = i + 1
    t_1 = i + 1
elif len(eo[0]) <= N // 3:
    for i in range(len(eo[0])):
        ans[3 * i + 2] = eo[0][i]
    t_0 = len(eo[0])
    t_1 = 0
elif len(eo[1]) <= N // 3:
    for i in range(len(eo[1])):
        ans[3 * i + 2] = eo[1][i]
    t_0 = 0
    t_1 = len(eo[1])

for i in range(N):
    if ans[i] != -1:
        continue
    if t_0 < len(eo[0]):
        ans[i] = eo[0][t_0]
        t_0 += 1
    else:
        ans[i] = eo[1][t_1]
        t_1 += 1

print(" ".join(list(map(str, [a + 1 for a in ans]))))

import sys

sys.setrecursionlimit(2 * 10**6)

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

def dfs(n, d):
    if depth[n] != -1:
        return
    depth[n] = d
    for nn in eAB[n]:
        dfs(nn, d + 1)
    return

N = int(input())
AB = [inpl() for i in range(N - 1)]

eAB = [[] for i in range(N)]
for a, b in AB:
    eAB[a - 1].append(b - 1)
    eAB[b - 1].append(a - 1)

depth = [-1 for i in range(N)]

dfs(0, 0)

eo = [[], []]
for i in range(N):
    eo[depth[i] % 2].append(i)

# print(eo)
ans = [-1 for i in range(N)]
if len(eo[0]) > N // 3 and len(eo[1]) > N // 3:
    for i in range(N // 3):
        ans[eo[0][i]] = 3 * i + 1
        ans[eo[1][i]] = 3 * i + 2
    t_0 = N // 3
    t_1 = N // 3
    if N % 3 > 0:
        ans[eo[0][N // 3]] = 3 * (N // 3) + 1
        t_0 += 1
    if N % 3 > 1:
        ans[eo[1][N // 3]] = 3 * (N // 3) + 2
        t_1 += 1
    # print(ans)
    for i, v in enumerate(eo[0][t_0:] + eo[1][t_1:]):
        ans[v] = 3 * (i + 1)
else:
    if len(eo[0]) <= N // 3:
        ni = 0
    else:
        ni = 1
    tmp = [True for i in range(N + 1)]
    for i in range(len(eo[ni])):
        ans[eo[ni][i]] = 3 * (i + 1)
        tmp[3 * (i + 1)] = False
    tmp = [i for i, t in enumerate(tmp) if t is True]
    j = 1
    for i in range(N):
        if ans[i] != -1:
            continue
        ans[i] = tmp[j]
        j += 1

print(" ".join(list(map(str, ans))))


import sys

sys.setrecursionlimit(10**6)

n = int(input())
ab = [list(map(int, input().split())) for _ in range(n - 1)]

adj = [[] for _ in range(n)]
for a, b in ab:
    a -= 1
    b -= 1
    adj[a].append(b)
    adj[b].append(a)

class Tree:
    WHITE = 0
    GRAY = -1
    BLACK = 1

    def __init__(self, adj):
        n = len(adj)
        self.adj = adj
        self.colors = [self.WHITE] * n
        self.depths = [-1] * n
        self.depth = 0

    def init(self):
        self.__init__(self.adj)

    def dfs(self, u):
        if self.colors[u] == self.BLACK:
            return

        self.colors[u] = self.GRAY
        self.depths[u] = self.depth

        for v in self.adj[u]:
            if self.colors[v] == self.WHITE:
                self.depth += 1
                self.dfs(v)
                self.depth -= 1

        self.colors[u] = self.BLACK

tree = Tree(adj)
tree.dfs(0)

ev = [i for i, e in enumerate(tree.depths) if e % 2 == 0]
od = [i for i, e in enumerate(tree.depths) if e % 2]

l_ev = len(ev)
l_od = len(od)

mod0 = [e for e in range(1, n + 1) if e % 3 == 0]
mod1 = [e for e in range(1, n + 1) if e % 3 == 1]
mod2 = [e for e in range(1, n + 1) if e % 3 == 2]

ans = [0] * n

def f(li1, li2):
    while li1 and li2:
        i = li1.pop()
        num = li2.pop()
        ans[i] = num

if l_ev > n / 3 and l_od > n / 3:
    f(ev, mod1)
    f(od, mod2)
    f(ev, mod0)
    f(od, mod0)

elif l_ev <= n / 3:
    f(ev, mod0)
    f(od, mod0)
    f(od, mod1)
    f(od, mod2)

else:
    f(od, mod0)
    f(ev, mod0)
    f(ev, mod1)
    f(ev, mod2)

print(*ans)


s = str(input())
if s == "AAA" or s == "BBB":
    input("No")
else:
    input("Yes")

s = str(input())
if s == "AAA" or s == "BBB":
    print("No")
else:
    print("Yes")

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02753/Python/s471253623.py", line 5, in <module>
    input("Yes")
EOFError: EOF when reading a line


s = int(input())
if s in "AAA-BBB":
    print("No")
else:
    print("Yes")

s = input()
if s in "AAA-BBB":
    print("No")
else:
    print("Yes")

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


s = input()
Q = int(input())
flag = True  # flagがTrueのとき、偶数回数の反転が行われている
cnt = 0
for _ in range(Q):
    query = list(map(str, input().split()))
    # tmp.append(query)
    if len(query) == 1:  # 1のqueryのとき
        cnt += 1
        if flag:
            flag = False
        else:
            flag = True
    else:
        f, c = query[1], query[2]
        if f == "1":  # 先頭に追加するもの
            if flag:
                s = c + s  # 偶数回の反転なら素直に先頭に追加する
            else:
                s += c  # 奇数会の反転なら後ろに追加する
        else:  # 末尾に追加する
            if flag:
                s += c
            else:
                s = c + s

if cnt % 2 == 1 and cnt != 0:
    s = s[::-1]
print(s)

S = input()
if "A" in S and "B" in S:
    print("Yes")
else:
    print("No")

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02753/Python/s625684460.py", line 2, in <module>
    Q = int(input())
EOFError: EOF when reading a line


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

x = []
cnt = 0
flag = True
while cnt < n:
    if flag:
        for j in range(a):
            if cnt + j >= n:
                break
            x.append(1)
        cnt += a
        flag = False
    else:
        for j in range(b):
            if cnt + j >= n:
                break
            x.append(0)
        cnt += b
        flag = True

cnt = 0
for i in range(n):
    if x[i] == 1:
        cnt += 1

print(cnt)

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

ans = n // (a + b) * a
rem = n % (a + b)
print(ans + min(rem, a))


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

blue_count = 0
while n != 0:
    # 青
    if n > a:
        n -= a
        blue_count += a
    else:
        blue_count += n
        n = 0
    if n > b:
        n -= b
    else:
        n = 0

print(blue_count)

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

blue_count = a * (n // (a + b))
n -= (a + b) * (n // (a + b))
if n >= a:
    blue_count += a
else:
    blue_count += n
print(blue_count)


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

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

temp_plus = ("1" * a) + ("0" * b)
temp = ""
while len(temp) <= n:
    temp += temp_plus

print(temp[0:n].count("1"))

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

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

temp = n // (a + b)
amari = n % (a + b)
result = temp * a

if amari >= a:
    result += a
else:
    result += amari

print(result)


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

current_n = N
b_cnt = 0
flag = True
while current_n != 0:
    if flag:
        if current_n - A > 0:
            current_n = current_n - A
            b_cnt += A
        else:
            b_cnt += current_n
            current_n = 0
        flag = False
    else:
        if current_n - B > 0:
            current_n = current_n - B
        else:
            current_n = 0
        flag = True

print(b_cnt)

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

q, r = divmod(N, A + B)

if r >= A:
    print(q * A + A)
else:
    print(q * A + r)


n, b, r = map(int, input().split())
ans = 0

while n > 0:
    ans += min(n, b)
    n -= b + r

print(ans)

n, b, r = map(int, input().split())

ans = n // (b + r) * b
n = n % (b + r)

ans += min(n, b)

print(ans)


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

ans = 0
while True:
    if n >= a:
        n -= a
        ans += a
    else:
        ans += n
        break

    if n >= b:
        n -= b
    else:
        break
print(ans)

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

ans = n // (a + b) * a
amari = n - (a + b) * (n // (a + b))
ans += min(amari, a)

print(ans)


n, a, b = map(int, input().split().rstrip())
k = n // (a + b)
r = n % (a + b)
print(k * a + min(r, a))

n, a, b = map(int, input().rstrip().split())
k = n // (a + b)
r = n % (a + b)
print(k * a + min(r, a))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02754/Python/s608778092.py", line 1, in <module>
    n, a, b = map(int, input().split().rstrip())
AttributeError: 'list' object has no attribute 'rstrip'


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

acnt = 0
bcnt = 0
while True:
    acnt += a
    if acnt + bcnt >= n:
        acnt -= (acnt + bcnt) - n
        break
    bcnt += b
    if acnt + bcnt >= n:
        break
print(acnt)

n, a, b = map(int, input().split())
amari = n % (a + b)
sho = n // (a + b)
if n <= a:
    print(n)
elif amari == 0:
    print(a * sho)
elif amari < a:
    print(a * sho + amari)
else:
    print(a * sho + a)


n, a, b = map(int, input().split())
s = "a" * a + "b" * b
S = s * (int(n / (a + b)) + 1)
print(S[:n].count("a"))

n, a, b = map(int, input().split())
if a == 0:
    print(0)
elif n <= a:
    print(n)
else:
    r = int(n / (a + b))
    if n % (a + b) < a:
        print(n - r * b)
    else:
        print(a * (r + 1))


n, a, b = map(int, input().split())
count = 0
bcount = 0
turn = 0
while count <= n:
    if turn % 2 == 0:
        if count + a <= n:
            count += a
            bcount += a
        else:
            bcount += n - count
            count += n - count

    else:
        if count + b <= n:
            count += b
        else:
            count += b
    turn += 1
print(bcount)

n, a, b = map(int, input().split())
count = 0
bcount = 0
ab = a + b

k = int(n / ab)
amari = n - k * ab
bcount += k * a
if amari >= a:
    bcount += a
else:
    bcount += amari

print(bcount)


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

ans = 0

while N > 0:
    red = min(N, A)
    ans += red
    N -= red
    blue = min(N, B)
    N -= blue
print(ans)

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

rep = N // (A + B)
ans = A * rep
diff = N - (A + B) * rep
ans += min(diff, A)
print(ans)


N, A, B = map(int, input().split())
capacity = N
is_a = True
cnt = 0

while capacity > 0:
    if is_a:
        ball = A
        cnt += min(capacity, ball)
    else:
        ball = B

    is_a = not is_a
    capacity -= min(capacity, ball)

print(cnt)

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

combo = A + B
num_of_combo = N // combo
remaining = N - combo * num_of_combo

print(num_of_combo * A + min(remaining, A))


import math

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

volume_A = A / 0.08
volume_B = B / 0.1

min_A, max_A = volume_A, volume_A
range_A = 1 / 0.08
min_B, max_B = volume_B, volume_B
range_B = 1 / 0.1

for i in range(math.floor(volume_A - range_A), math.ceil(volume_A + range_A)):
    if math.floor(i * 0.08) == A:
        min_A = min(min_A, i)
        max_A = max(max_A, i)

for j in range(math.floor(volume_B - range_B), math.ceil(volume_B + range_B)):
    if math.floor(j * 0.1) == B:
        min_B = min(min_B, j)
        max_B = max(max_B, j)

ans_A = set()
for i in range(min_A, max_A + 1):
    ans_A.add(i)

ans_B = set()
for j in range(min_B, max_B + 1):
    ans_B.add(j)

ans = ans_A & ans_B

if len(ans) == 0:
    print(-1)
else:
    print(min(ans))

import math

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

volume_A = math.floor(A / 0.08)
volume_B = math.floor(B / 0.1)

min_A, max_A = math.inf, -math.inf
range_A = math.floor(1 / 0.08)
min_B, max_B = math.inf, -math.inf
range_B = math.floor(1 / 0.1)
# print(range_A)
# print(range_B)

for i in range(volume_A - range_A, volume_A + range_A):
    if math.floor(i * 0.08) == A:
        min_A = min(min_A, i)
        max_A = max(max_A, i)

for j in range(volume_B - range_B, volume_B + range_B):
    if math.floor(j * 0.1) == B:
        min_B = min(min_B, j)
        max_B = max(max_B, j)

ans_A = set()
for i in range(min_A, max_A + 1):
    ans_A.add(i)
# print(ans_A)

ans_B = set()
for j in range(min_B, max_B + 1):
    ans_B.add(j)
# print(ans_B)

ans = ans_A & ans_B

if len(ans) == 0:
    print(-1)
else:
    print(min(ans))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02755/Python/s079173074.py", line 24, in <module>
    for i in range(min_A, max_A + 1):
TypeError: 'float' object cannot be interpreted as an integer


A, B = map(int, input().split())
a = [i for i in range(1, 1001) if int(i * 0.08) == A]
b = [i for i in range(1, 1001) if int(i * 0.1) == B]
print(min(set(a) & set(b)))

A, B = map(int, input().split())
a = [i for i in range(1, 1001) if int(i * 0.08) == A]
b = [i for i in range(1, 1001) if int(i * 0.1) == B]
c = set(a) & set(b)
if len(c):
    print(min(c))
else:
    print(-1)


import math

a, b = map(int, input().split())
for i in range(1, 101):
    if a == math.floor(i * 0.08):
        for j in range(1, 101):
            if b == math.floor(j * 0.1):
                if i == j:
                    break
        else:
            continue
        break
else:
    print(-1)
print(j)

a, b = map(int, input().split())
for i in range(1, 1001):
    if a == int(i * 0.08) and b == int(i * 0.1):
        print(i)
        break
else:
    print(-1)


S = list(input())
Q = int(input())

Query = [list(input()) for i in range(Q)]

for i in range(Q):
    if Query[i][0] == "1":
        S.reverse()
    else:
        if Query[i][2] == "1":
            S.insert(0, Query[i][4])
        else:
            S.append(Query[i][4])

print("".join(S))

from collections import deque

S = list(input())
Q = int(input())

S = deque(S)

Query = [list(input()) for i in range(Q)]

rev_cnt = 0

for i in range(Q):
    if Query[i][0] == "1":
        rev_cnt += 1
    else:
        if Query[i][2] == "1":
            if rev_cnt % 2 == 1:
                S.append(Query[i][4])
            else:
                S.appendleft(Query[i][4])
        else:
            if rev_cnt % 2 == 1:
                S.appendleft(Query[i][4])
            else:
                S.append(Query[i][4])

if rev_cnt % 2 == 1:
    while len(S) != 0:
        print(S.pop(), end="")
else:
    while len(S) != 0:
        print(S.popleft(), end="")

print()


s = input()
q = int(input())
flag = True
for _ in range(q):
    query = input().split()
    if query[0] == "1":
        flag = not flag
    else:
        if (query[1] == "1" and flag) or (query[1] == "2" and not flag):
            s = query[2] + s
        else:
            s = s + query[2]
sf = 1 if flag else -1
print(s[::sf])

from collections import deque

s = deque(input())
q = int(input())
flag = True
for _ in range(q):
    query = input().split()
    if query[0] == "1":
        flag = not flag
    else:
        if (query[1] == "1" and flag) or (query[1] == "2" and not flag):
            s.appendleft(query[2])
        else:
            s.append(query[2])
if not flag:
    s.reverse()
print("".join(s))


S = list(input())
Q = int(input())

for _ in range(Q):
    q = input()
    if len(q) == 1:
        S = list(S)
        S.reverse()
        S = "".join(S)
    else:
        T, F, C = q.split()
        if int(F) == 1:
            S = C + S
        else:
            S = S + C

print(S)

from collections import deque

S = list(input())
Q = int(input())

d = deque(S)
head = "l"

for _ in range(Q):
    q = input()
    if len(q) == 1:
        if head == "l":
            head = "r"
        else:
            head = "l"
    else:
        T, F, C = q.split()
        if int(F) == 1:
            if head == "l":
                d.appendleft(C)
            else:
                d.append(C)
        else:
            if head == "l":
                d.append(C)
            else:
                d.appendleft(C)
if head == "l":
    print("".join(list(d)))
else:
    print("".join(list(d)[::-1]))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p02756/Python/s030720432.py", line 13, in <module>
    S = C + S
TypeError: can only concatenate str (not "list") to str


s = input()
q = int(input())

def s_add(r, f):
    if r % 2 == 0:
        if f == 1:
            return True
        else:
            return False
    else:
        if f == 1:
            return False
        else:
            return True

cnt = 0
for _ in range(q):
    query = input()
    if query == "1":
        cnt += 1
    else:
        z, f, c = query.split()
        if s_add(cnt, int(f)):
            s = c + s
        else:
            s += c

if cnt % 2 == 0:
    print(s)
else:
    print(s[::-1])

s = input()
q = int(input())
left = ""
right = ""

def s_add(r, f):
    if r % 2 == 0:
        if f == 1:
            return True
        else:
            return False
    else:
        if f == 1:
            return False
        else:
            return True

cnt = 0
for _ in range(q):
    query = input()
    if query == "1":
        cnt += 1
    else:
        z, f, c = query.split()
        if s_add(cnt, int(f)):
            left += c
        else:
            right += c

if cnt % 2 == 0:
    print(left[::-1] + s + right)
else:
    print(right[::-1] + s[::-1] + left)


from collections import deque

def main():
    S = list(input())
    D = deque(S)
    Q = int(input())
    T = [tuple(map(str, input().split())) for _ in range(Q)]

    for t in T:
        if t[0] == "1":
            D.reverse()
        else:
            if t[1] == "1":
                D.appendleft(t[2])
            else:
                D.append(t[2])

    print("".join(D))

if __name__ == "__main__":
    main()

from collections import deque

def main():
    S = list(input())
    D = deque(S)
    Q = int(input())
    T = [tuple(map(str, input().split())) for _ in range(Q)]
    r = False

    for t in T:
        if t[0] == "1" and r == False:
            r = True
        elif t[0] == "1" and r == True:
            r = False
        else:
            if t[1] == "1" and r == False:
                D.appendleft(t[2])
            elif t[1] == "1" and r == True:
                D.append(t[2])
            elif t[1] == "2" and r == False:
                D.append(t[2])
            elif t[1] == "2" and r == True:
                D.appendleft(t[2])

    if r == False:
        print("".join(D))
    else:
        D.reverse()
        print("".join(D))

if __name__ == "__main__":
    main()


S = str(input())
Q = int(input())

topFlg = True

for _ in range(Q):
    query = list(map(str, input().split()))
    if query[0] == "1":
        topFlg = not (topFlg)
    else:
        if query[1] == "1":
            S = query[2] + S if topFlg else S + query[2]
        else:
            S = S + query[2] if topFlg else query[2] + S

print(S) if topFlg else print(S[::-1])

S = str(input())
Q = int(input())

topFlg = True

leftStr = ""
rightStr = ""

for _ in range(Q):
    query = list(map(str, input().split()))
    if query[0] == "1":
        topFlg = not (topFlg)
    else:
        if query[1] == "1":
            if topFlg:
                leftStr = query[2] + leftStr
            else:
                rightStr += query[2]
        else:
            if topFlg:
                rightStr += query[2]
            else:
                leftStr = query[2] + leftStr

print(leftStr + S + rightStr if topFlg else rightStr[::-1] + S[::-1] + leftStr[::-1])


from collections import deque

S = deque(input())
Q = int(input())
Queries = [input().split() for _ in range(Q)]

need_reverse = False

for q in Queries:
    if q[0] == "1":
        need_reverse = not need_reverse
    else:
        if q[1] == "1":
            if not need_reverse:
                S.appendleft(q[2])
            else:
                S.append(q[2])
        else:
            if not need_reverse:
                S.append(q[2])
            else:
                S.appendleft(q[2])

print(S if not need_reverse else S[::-1])

from collections import deque

S = deque(input())
Q = int(input())
Queries = [input().split() for _ in range(Q)]

need_reverse = False

for q in Queries:
    if q[0] == "1":
        need_reverse = not need_reverse
    else:
        if q[1] == "1":
            if not need_reverse:
                S.appendleft(q[2])
            else:
                S.append(q[2])
        else:
            if not need_reverse:
                S.append(q[2])
            else:
                S.appendleft(q[2])

S = "".join(S)
print(S if not need_reverse else S[::-1])


# D - String Formation

S = input()
Q = int(input())
rev = False

for _ in range(Q):
    T = [t for t in input().split()]
    t = int(T[0])
    if t == 1:
        rev = not rev
    if t == 2:
        f, c = int(T[1]), T[2]
        if f == 1:
            if rev:
                S = S + c
            else:
                S = c + S
        if f == 2:
            if rev:
                S = c + S
            else:
                S = S + c

print(S if not rev else S[::-1])

# D - String Formation

from collections import deque

S = deque([s for s in input()])
Q = int(input())
rev = False

for _ in range(Q):
    T = [t for t in input().split()]
    t = int(T[0])
    if t == 1:
        rev = not rev
    if t == 2:
        f, c = int(T[1]), T[2]
        if f == 1:
            if rev:
                S.append(c)
            else:
                S.appendleft(c)
        if f == 2:
            if rev:
                S.appendleft(c)
            else:
                S.append(c)

S = "".join(list(S))
print(S if not rev else S[::-1])


s = list(input())
q = int(input())
rev = False

for _ in range(q):
    query = input().split()
    t = query[0]
    if t == "1":
        rev = not rev
        continue
    f = query[1]
    c = query[2]
    if not rev and f == "2" or rev and f == "1":
        s.append(c)
    else:
        s.insert(0, c)
if rev:
    s = reversed(s)
print("".join(s))

from collections import deque

s = input()
q = int(input())

deq = deque(s)
rev = False

for _ in range(q):
    query = input().split()
    t = query[0]
    if t == "1":
        rev = not rev
        continue
    f = query[1]
    c = query[2]
    if not rev and f == "2" or rev and f == "1":
        deq.append(c)
    else:
        deq.appendleft(c)
if rev:
    deq = reversed(deq)
print("".join(deq))


s = input()
q = int(input())
flag = 0
cnt = 0

for i in range(q):
    t = input()
    if len(t) == 1:
        cnt += 1
        if flag == 0:
            flag = 1
        elif flag == 1:
            flag = 0
    else:
        _, a, b = (str(i) for i in t.split())
        if a == "1":
            if flag == 0:
                s = b + s
            elif flag == 1:
                s = s + b
        elif a == "2":
            if flag == 0:
                s = s + b
            elif flag == 1:
                s = b + s

if cnt % 2 == 0:
    print(s)
else:
    print(s[::-1])

def main():
    s = input()
    q = int(input())
    flag = 0
    cnt = 0
    front = []
    back = []

    for i in range(q):
        t = input()
        if len(t) == 1:
            cnt += 1
            if flag == 0:
                flag = 1
            elif flag == 1:
                flag = 0
        else:
            _, a, b = (str(i) for i in t.split())
            if a == "1":
                if flag == 0:
                    front.append(b)
                elif flag == 1:
                    back.append(b)
            elif a == "2":
                if flag == 0:
                    back.append(b)
                elif flag == 1:
                    front.append(b)

    if cnt % 2 == 0:
        front = front[::-1]
        s = "".join(front) + s + "".join(back)
    else:
        back = back[::-1]
        s = "".join(back) + s[::-1] + "".join(front)

    print(s)

if __name__ == "__main__":
    main()


from collections import deque

s = deque(input())
len_queries = int(input())
queries = [input().split() for _ in range(len_queries)]

is_forward = True
for query in queries:
    if "1" == query[0]:
        is_forward = not is_forward
    else:
        if is_forward:
            insert_index = 0 if "1" == query[1] else len(s)
            s.insert(insert_index, query[2])
        else:
            insert_index = len(s) if "1" == query[1] else 0
            s.insert(insert_index, query[2])
if not is_forward:
    s.reverse()
print("".join(s))

from collections import deque

s = deque(input())
len_queries = int(input())
queries = [input().split() for _ in range(len_queries)]

is_forward = True
for query in queries:
    if "1" == query[0]:
        is_forward = not is_forward
    else:
        if is_forward:
            if "1" == query[1]:
                s.appendleft(query[2])
            else:
                s.append(query[2])
        else:
            if "1" == query[1]:
                s.append(query[2])
            else:
                s.appendleft(query[2])
if not is_forward:
    s.reverse()
print("".join(s))


s = input()
Q = int(input())
flag = True  # flagがTrueのとき、偶数回数の反転が行われている
cnt = 0
query = [list(map(str, input().split())) for _ in range(Q)]
for i in range(Q):
    a = query[i]
    # tmp.append(query)
    if len(a) == 1:  # 1のqueryのとき
        cnt += 1
        if flag:
            flag = False
        else:
            flag = True
    else:
        f, c = a[1], a[2]
        if f == "1":  # 先頭に追加するもの
            if flag:
                s = c + s  # 偶数回の反転なら素直に先頭に追加する
            else:
                s += c  # 奇数会の反転なら後ろに追加する
        else:  # 末尾に追加する
            if flag:
                s += c
            else:
                s = c + s

if cnt % 2 == 1 and cnt != 0:
    s = s[::-1]
print(s)

s = input()
Q = int(input())
flag = True  # flagがTrueのとき、偶数回数の反転が行われている
cnt = 0
query = [list(map(str, input().split())) for _ in range(Q)]
before = []  # 先頭に追加する時
after = []  # 末尾に追加する時
for i in range(Q):
    a = query[i]
    if len(a) == 1:  # 1のqueryのとき
        cnt += 1
        if flag:
            flag = False
        else:
            flag = True
    else:
        f, c = a[1], a[2]
        if f == "1":  # 先頭に追加するもの
            if flag:
                # s = c + s  # 偶数回の反転なら素直に先頭に追加する
                before.append(c)
            else:
                # s += c  # 奇数会の反転なら後ろに追加する
                after.append(c)
        else:  # 末尾に追加する
            if flag:
                # s += c  # 末尾に追加
                after.append(c)
            else:
                # s = c + s  # 先頭に追加
                before.append(c)
before.reverse()
# print(before)
# print(s)
# print(after)
s = "".join(before) + s + "".join(after)
if cnt % 2 == 1 and cnt != 0:
    s = s[::-1]
print(s)


s = input()
q = int(input())
reverseFlag = False

def getQuery():
    yield input().split()

for _ in range(q):
    for query in getQuery():
        if query[0] == "1":
            reverseFlag = not reverseFlag
        else:
            if query[1] == "1":
                s = (s + query[2]) if reverseFlag else (query[2] + s)
            else:
                s = (query[2] + s) if reverseFlag else (s + query[2])

if reverseFlag:
    s = s[::-1]

print(s)

from collections import deque

s = input()
q = int(input())
d = deque(s)
reverseFlag = False

def getQuery():
    yield input().split()

for _ in range(q):
    for query in getQuery():
        if query[0] == "1":
            reverseFlag = not reverseFlag
        else:
            if query[1] == "1":
                if reverseFlag:
                    d.append(query[2])
                else:
                    d.appendleft(query[2])
            else:
                if reverseFlag:
                    d.appendleft(query[2])
                else:
                    d.append(query[2])

ans = "".join(d)
if reverseFlag:
    ans = ans[::-1]

print(ans)


from collections import deque

s = deque(list(input()))
n = int(input())
q = [list(input().split()) for _ in range(n)]
for tfc in q:
    if tfc[0] == "1":
        s.reverse()
    else:
        if tfc[1] == "1":
            s.appendleft(tfc[2])
        else:
            s.append(tfc[2])

print("".join(s))

from collections import deque

s = deque(list(input()))
n = int(input())
q = [list(input().split()) for _ in range(n)]
rev = False

for tfc in q:
    if tfc[0] == "1" and rev is False:
        rev = True
    elif tfc[0] == "1" and rev is True:
        rev = False
    elif rev is False:
        if tfc[1] == "1":
            s.appendleft(tfc[2])
        else:
            s.append(tfc[2])
    elif rev is True:
        if tfc[1] == "1":
            s.append(tfc[2])
        else:
            s.appendleft(tfc[2])

if rev:
    s.reverse()
print("".join(s))


S = input()
Q = int(input())
reverseCount = 0
for _ in range(Q):
    query = input()
    if len(query) == 1:
        reverseCount += 1
    else:
        _, F, C = query.split(" ")
        if (int(F) + reverseCount) % 2 == 1:
            S = C + S
        else:
            S = S + C
if reverseCount % 2 == 0:
    print(S)
else:
    print(S[::-1])

S = input()
Q = int(input())
reverseCount = 0
pre = ""
pro = ""
for _ in range(Q):
    query = input()
    if len(query) == 1:
        reverseCount += 1
    else:
        _, F, C = query.split(" ")
        if (int(F) + reverseCount) % 2 == 1:
            pre = C + pre
        else:
            pro = pro + C
S = pre + S + pro
if reverseCount % 2 == 0:
    print(S)
else:
    print(S[::-1])


s = input()
q = int(input())
rev = False
for _ in range(q):
    query = input()
    if query == "1":
        rev = not rev
    else:
        _, f, c = query.split(" ")
        if f == "1":
            if rev:
                s = s + c
            else:
                s = c + s
        else:
            if rev:
                s = c + s
            else:
                s = s + c

if rev:
    s = s[::-1]
print(s)

s = input()
q = int(input())
rev = False
L = ""
R = ""
for _ in range(q):
    query = input()
    if query == "1":
        rev = not rev
    else:
        _, f, c = query.split(" ")
        if f == "1":
            if rev:
                R = R + c
            else:
                L = c + L
        else:
            if rev:
                L = c + L
            else:
                R = R + c

if rev:
    s = s[::-1]
    L = L[::-1]
    R = R[::-1]
    print(R + s + L)
else:
    print(L + s + R)


import collections

S = input()
Q = int(input())

d = collections.deque(S)

for _ in range(Q):
    Qi = input()
    if Qi == "1":
        d.reverse()
    else:
        T, F, C = Qi.split()
        if F == "1":
            d.appendleft(C)
        else:
            d.append(C)

print("".join(d))

import collections

class Formatter:
    def __init__(self, s):
        self._d = collections.deque(s)
        self._d_reverse = collections.deque(reversed(s))

    def reverse(self):
        self._d, self._d_reverse = self._d_reverse, self._d

    def append(self, s):
        self._d.append(s)
        self._d_reverse.appendleft(s)

    def appendleft(self, s):
        self._d.appendleft(s)
        self._d_reverse.append(s)

    def __iter__(self):
        return iter(self._d)

S = input()
Q = int(input())

d = Formatter(S)

for _ in range(Q):
    Qi = input()
    if Qi == "1":
        d.reverse()
    else:
        T, F, C = Qi.split()
        if F == "1":
            d.appendleft(C)
        else:
            d.append(C)

print("".join(d))


s = str(input())
n = int(input())

for _ in range(n):
    q = input()

    # 反転の場合
    if q[0] == "1":
        s = s[::-1]
        continue

    # q = q.split()

    if q[2] == "1":
        s = q[4] + s

    if q[2] == "2":
        s = s + q[4]

print(s)

s = str(input())
n = int(input())

stat = 0
front = ""
back = ""

for _ in range(n):
    q = input()

    # 反転の場合
    if q[0] == "1":
        stat = (stat + 1) % 2
        continue

    judge = int(q[2])
    if stat == 1:
        if judge == 1:
            judge = 2
        elif judge == 2:
            judge = 1

    if judge == 1:
        front = q[4] + front

    if judge == 2:
        back = back + q[4]

s = front + s + back
if stat == 1:
    s = s[::-1]

print(s)