Input:
n,m = list(map(int,input().split()))

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

bc =[]

for i in range(m):

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

    bc.append((b,c))

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

newcard=[]

for b,c in bc:

    newcard.extend([c]*b)

    if(len(newcard)>=n):

        break

size = min(n,len(newcard))

a.sort()

for i in range(size):

    if(newcard[i]>a[i]):

        a[i]=newcard[i]

    else:

        break

print((sum(a)))

import sys

input = sys.stdin.readline

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

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

bc =[]

for i in range(m):

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

    bc.append((b,c))

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

newcard=[]

for b,c in bc:

    newcard.extend([c]*b)

    if(len(newcard)>=n):

        break

a += newcard

a.sort(reverse=True)

print((sum(a[:n])))

n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
bc = []
for i in range(m):
    b, c = list(map(int, input().split()))
    bc.append((b, c))
bc.sort(key=lambda x: x[1], reverse=True)
newcard = []
for b, c in bc:
    newcard.extend([c] * b)
    if len(newcard) >= n:
        break
size = min(n, len(newcard))
a.sort()
for i in range(size):
    if newcard[i] > a[i]:
        a[i] = newcard[i]
    else:
        break
print((sum(a)))

import sys

input = sys.stdin.readline
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
bc = []
for i in range(m):
    b, c = list(map(int, input().split()))
    bc.append((b, c))
bc.sort(key=lambda x: x[1], reverse=True)
newcard = []
for b, c in bc:
    newcard.extend([c] * b)
    if len(newcard) >= n:
        break
a += newcard
a.sort(reverse=True)
print((sum(a[:n])))

+import sys
+
+input = sys.stdin.readline
-size = min(n, len(newcard))
-a.sort()
-for i in range(size):
-    if newcard[i] > a[i]:
-        a[i] = newcard[i]
-    else:
-        break
-print((sum(a)))
+a += newcard
+a.sort(reverse=True)
+print((sum(a[:n])))


Input:
# エラトステネスの篩, フェルマーの小定理

max_A = 1000000

N = int(eval(input()))

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

sieve = [0] * (max_A + 1)

sieve[0] = -1

sieve[1] = -1

for i in range(2, max_A + 1):

    if sieve[i] != 0:

        continue

    sieve[i] = i

    for j in range(i * i, max_A + 1, i):

        if sieve[j] == 0:

            sieve[j] = i

lcm_factors = {}

for i in range(N):

    t = []

    a = A[i]

    while a != 1:

        if len(t) != 0 and t[-1][0] == sieve[a]:

            t[-1][1] += 1

        else:

            t.append([sieve[a], 1])

        a //= sieve[a]

    for k, v in t:

        if k not in lcm_factors or lcm_factors[k] < v:

            lcm_factors[k] = v

lcm = 1

for k in lcm_factors:

    for i in range(lcm_factors[k]):

        lcm *= k

        lcm %= 1000000007

result = 0

for i in range(N):

    result += lcm * pow(A[i], 1000000007-2, 1000000007)

    result %= 1000000007

print(result)

# エラトステネスの篩, フェルマーの小定理

max_A = 1000000

N = int(eval(input()))

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

m = 1000000007

sieve = [0] * (max_A + 1)

sieve[0] = -1

sieve[1] = -1

for i in range(2, max_A + 1):

    if sieve[i] != 0:

        continue

    sieve[i] = i

    for j in range(i * i, max_A + 1, i):

        if sieve[j] == 0:

            sieve[j] = i

lcm_factors = {}

for i in range(N):

    t = []

    a = A[i]

    while a != 1:

        if len(t) != 0 and t[-1][0] == sieve[a]:

            t[-1][1] += 1

        else:

            t.append([sieve[a], 1])

        a //= sieve[a]

    for k, v in t:

        if k not in lcm_factors or lcm_factors[k] < v:

            lcm_factors[k] = v

lcm = 1

for k in lcm_factors:

    for i in range(lcm_factors[k]):

        lcm *= k

        lcm %= m

result = 0

for i in range(N):

    result += lcm * pow(A[i], m - 2, m)

    result %= m

print(result)

# エラトステネスの篩, フェルマーの小定理
max_A = 1000000
N = int(eval(input()))
A = list(map(int, input().split()))
sieve = [0] * (max_A + 1)
sieve[0] = -1
sieve[1] = -1
for i in range(2, max_A + 1):
    if sieve[i] != 0:
        continue
    sieve[i] = i
    for j in range(i * i, max_A + 1, i):
        if sieve[j] == 0:
            sieve[j] = i
lcm_factors = {}
for i in range(N):
    t = []
    a = A[i]
    while a != 1:
        if len(t) != 0 and t[-1][0] == sieve[a]:
            t[-1][1] += 1
        else:
            t.append([sieve[a], 1])
        a //= sieve[a]
    for k, v in t:
        if k not in lcm_factors or lcm_factors[k] < v:
            lcm_factors[k] = v
lcm = 1
for k in lcm_factors:
    for i in range(lcm_factors[k]):
        lcm *= k
        lcm %= 1000000007
result = 0
for i in range(N):
    result += lcm * pow(A[i], 1000000007 - 2, 1000000007)
    result %= 1000000007
print(result)

+    result += lcm * pow(A[i], m - 2, m)


Input:
import heapq

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

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

bc = []

for _ in range(m):

    b, c = (int(x) for x in input().split())

    bc.append([b, c])

bc = sorted(bc, key=lambda x: -x[1])

heapq.heapify(a)

for i in range(m):

    count = 0

    if bc[i][1] < a[0]:

        break

    while a[0] < bc[i][1] and count < bc[i][0]:

        heapq.heappop(a)

        heapq.heappush(a,bc[i][1])

        count += 1

print((sum(a)))

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

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

A.sort(reverse=True)

BC = []

for _ in range(M):

    B, C = (int(x) for x in input().split())

    BC.append([B, C])

BC = sorted(BC, key=lambda x: -x[1])

index = 0

ans = 0

while index < M and len(A) and A[-1] < BC[index][1]:

    b, c = BC[index]

    count = 0

    while len(A) and A[-1] < c and count < b:

        A.pop()

        ans += c

        count += 1

    index += 1

print((sum(A)+ans))

import heapq

n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
bc = []
for _ in range(m):
    b, c = (int(x) for x in input().split())
    bc.append([b, c])
bc = sorted(bc, key=lambda x: -x[1])
heapq.heapify(a)
for i in range(m):
    count = 0
    if bc[i][1] < a[0]:
        break
    while a[0] < bc[i][1] and count < bc[i][0]:
        heapq.heappop(a)
        heapq.heappush(a, bc[i][1])
        count += 1
print((sum(a)))

N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort(reverse=True)
BC = []
for _ in range(M):
    B, C = (int(x) for x in input().split())
    BC.append([B, C])
BC = sorted(BC, key=lambda x: -x[1])
index = 0
ans = 0
while index < M and len(A) and A[-1] < BC[index][1]:
    b, c = BC[index]
    count = 0
    while len(A) and A[-1] < c and count < b:
        A.pop()
        ans += c
        count += 1
    index += 1
print((sum(A) + ans))

-    b, c = (int(x) for x in input().split())

+    B, C = (int(x) for x in input().split())

+while index < M and len(A) and A[-1] < BC[index][1]:

-    while a[0] < bc[i][1] and count < bc[i][0]:

+    while len(A) and A[-1] < c and count < b:


Input:
k=int(eval(input()))

L=[]

def f(d,now,L):

  L.append(now)

  if d==10:

    return

  for j in range(-1,2):

    v=now%10+j

    if 0<=v<=9:

      f(d+1,now*10+v,L)

for l in range(1,10):

  f(1,l,L)

L.sort()

print((L[k-1]))

from collections import deque

k=int(eval(input()))

lunlun=deque(i for i in range(1,10))

for _ in range(k-1):

  p=lunlun.popleft()

  if p%10!=0:

    lunlun.append(10*p+p%10-1)

  lunlun.append(10*p+p%10)

  if p%10!=9:

    lunlun.append(10*p+p%10+1)

print((lunlun.popleft()))

k = int(eval(input()))
L = []

def f(d, now, L):
    L.append(now)
    if d == 10:
        return
    for j in range(-1, 2):
        v = now % 10 + j
        if 0 <= v <= 9:
            f(d + 1, now * 10 + v, L)

for l in range(1, 10):
    f(1, l, L)
L.sort()
print((L[k - 1]))

from collections import deque

k = int(eval(input()))
lunlun = deque(i for i in range(1, 10))
for _ in range(k - 1):
    p = lunlun.popleft()
    if p % 10 != 0:
        lunlun.append(10 * p + p % 10 - 1)
    lunlun.append(10 * p + p % 10)
    if p % 10 != 9:
        lunlun.append(10 * p + p % 10 + 1)
print((lunlun.popleft()))

+lunlun = deque(i for i in range(1, 10))

+        lunlun.append(10 * p + p % 10 - 1)

+        lunlun.append(10 * p + p % 10 + 1)


Input:
eval(input())

ls = list(map(int, input().split(' ')))

ls.sort(reverse=True)

def main(ls):

    if ls.count(0) > 0:

        print((0))

        return

    result = 1

    for i in ls:

        result *= i

        if result > 10 ** 18:

            print((-1))

            return

    print(result)

main(ls)

eval(input())

ls = list(map(int, input().split(' ')))

if ls.count(0) > 0:

    result = 0

else:

    result = 1

    for i in ls:

        result *= i

        if result > 10 ** 18:

            result = -1

            break

print(result)

eval(input())
ls = list(map(int, input().split(" ")))
ls.sort(reverse=True)

def main(ls):
    if ls.count(0) > 0:
        print((0))
        return
    result = 1
    for i in ls:
        result *= i
        if result > 10**18:
            print((-1))
            return
    print(result)

main(ls)

eval(input())
ls = list(map(int, input().split(" ")))
if ls.count(0) > 0:
    result = 0
else:
    result = 1
    for i in ls:
        result *= i
        if result > 10**18:
            result = -1
            break
print(result)

-ls.sort(reverse=True)
-def main(ls):
-    if ls.count(0) > 0:
-        print((0))
-        return
+if ls.count(0) > 0:
+    result = 0
+else:
-            print((-1))
-            return
-    print(result)
-main(ls)
+            result = -1
+            break
+print(result)


Input:
import sys

input = sys.stdin.readline

sys.setrecursionlimit(10**6)

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

AB = [[int(x) for x in input().split()] for _ in range(N-1)]

PX = [[int(x) for x in input().split()] for _ in range(Q)]

g = [[] for _ in range(N+1)]

for a,b in AB:

    g[a].append(b)

    g[b].append(a)

cnt = [0] * (N+1)

for p,x in PX:

    cnt[p] += x

def dfs(v, p, add):

    cnt[v] += add

    for nv in g[v]:

        if nv == p:

            continue

        dfs(nv, v, cnt[v])

dfs(1, 0, 0)

print((' '.join(map(str, cnt[1:]))))

import sys

input = sys.stdin.readline

sys.setrecursionlimit(10**6)

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

g = [[] for _ in range(N+1)]

for i in range(N-1):

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

    g[a].append(b)

    g[b].append(a)

cnt = [0] * (N+1)

for i in range(Q):

    p, x = list(map(int, input().split()))

    cnt[p] += x

def dfs(v, p, add):

    cnt[v] += add

    for nv in g[v]:

        if nv == p:

            continue

        dfs(nv, v, cnt[v])

dfs(1, 0, 0)

print((' '.join(map(str, cnt[1:]))))

import sys

input = sys.stdin.readline
sys.setrecursionlimit(10**6)
N, Q = list(map(int, input().split()))
AB = [[int(x) for x in input().split()] for _ in range(N - 1)]
PX = [[int(x) for x in input().split()] for _ in range(Q)]
g = [[] for _ in range(N + 1)]
for a, b in AB:
    g[a].append(b)
    g[b].append(a)
cnt = [0] * (N + 1)
for p, x in PX:
    cnt[p] += x

def dfs(v, p, add):
    cnt[v] += add
    for nv in g[v]:
        if nv == p:
            continue
        dfs(nv, v, cnt[v])

dfs(1, 0, 0)
print((" ".join(map(str, cnt[1:]))))

import sys

input = sys.stdin.readline
sys.setrecursionlimit(10**6)
N, Q = list(map(int, input().split()))
g = [[] for _ in range(N + 1)]
for i in range(N - 1):
    a, b = list(map(int, input().split()))
    g[a].append(b)
    g[b].append(a)
cnt = [0] * (N + 1)
for i in range(Q):
    p, x = list(map(int, input().split()))
    cnt[p] += x

def dfs(v, p, add):
    cnt[v] += add
    for nv in g[v]:
        if nv == p:
            continue
        dfs(nv, v, cnt[v])

dfs(1, 0, 0)
print((" ".join(map(str, cnt[1:]))))

-AB = [[int(x) for x in input().split()] for _ in range(N - 1)]

-PX = [[int(x) for x in input().split()] for _ in range(Q)]

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

+    p, x = list(map(int, input().split()))


Input:
n=int(eval(input()))

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

dp=[float('inf')]*n

dp[0]=0

dp[1]=abs(H[1]-H[0])

for i in range(2,n):

  dp[i]=min(dp[i],dp[i-1]+abs(H[i]-H[i-1]))

  dp[i]=min(dp[i],dp[i-2]+abs(H[i]-H[i-2]))

print((dp[-1]))

n=int(eval(input()))

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

dp=[0]*n

dp[1]=abs(H[1]-H[0])

for i in range(2,n):

  dp[i]=min(dp[i-1]+abs(H[i]-H[i-1]),dp[i-2]+abs(H[i]-H[i-2]))

print((dp[-1]))

n = int(eval(input()))
H = list(map(int, input().split()))
dp = [float("inf")] * n
dp[0] = 0
dp[1] = abs(H[1] - H[0])
for i in range(2, n):
    dp[i] = min(dp[i], dp[i - 1] + abs(H[i] - H[i - 1]))
    dp[i] = min(dp[i], dp[i - 2] + abs(H[i] - H[i - 2]))
print((dp[-1]))

n = int(eval(input()))
H = list(map(int, input().split()))
dp = [0] * n
dp[1] = abs(H[1] - H[0])
for i in range(2, n):
    dp[i] = min(dp[i - 1] + abs(H[i] - H[i - 1]), dp[i - 2] + abs(H[i] - H[i - 2]))
print((dp[-1]))


Input:
def main():

    S = eval(input())

    if S[0] == "B":

        K = "WB"

    else:

        K = "BW"

    cnt = 0

    for i in range(len(S)-1):

        if S[i:i+2] == K:

            cnt += 1

    if S[0] == S[-1]:

        print((2 * cnt))

    else:

        print((1 + 2 * cnt))

main()

def main():

    S = eval(input())

    if S[0] == "B":

        K = "WB"

    else:

        K = "BW"

    cnt = S.count(K)

    if S[0] == S[-1]:

        print((2 * cnt))

    else:

        print((1 + 2 * cnt))

main()

def main():
    S = eval(input())
    if S[0] == "B":
        K = "WB"
    else:
        K = "BW"
    cnt = 0
    for i in range(len(S) - 1):
        if S[i : i + 2] == K:
            cnt += 1
    if S[0] == S[-1]:
        print((2 * cnt))
    else:
        print((1 + 2 * cnt))

main()

-    cnt = 0
-    for i in range(len(S) - 1):
-        if S[i : i + 2] == K:
-            cnt += 1
+    cnt = S.count(K)


Input:
#!/usr/bin/env python

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

import sys

UNVISITED, VISITED_IN_STACK, POPPED_OUT = 0, 1, 2

def generate_adj_matrix(v_info):

    for v_detail in v_info:

        v_adj_list = v_detail[2:]

        assert len(v_adj_list) == int(v_detail[1])

        for each in v_adj_list:

            init_adj_matrix[int(v_detail[0]) - 1][int(each) - 1] = 1

    return init_adj_matrix

def graph_dfs(v_init):

    global time

    # init the first node of overall graph iterations(times >= 1)

    vertex_visit_stack.append(v_init)

    vertex_status_list[v_init] = VISITED_IN_STACK

    vertex_d_time[v_init] += time

    # init end

    while len(vertex_visit_stack) > 1:

        current_vertex = vertex_visit_stack[-1]

        next_vertex = get_adj_vertices(vertex=current_vertex)

        if next_vertex:

            if vertex_status_list[next_vertex] is UNVISITED:

                vertex_status_list[next_vertex] = VISITED_IN_STACK

                time += 1

                vertex_d_time[next_vertex] += time

                vertex_visit_stack.append(next_vertex)

        else:

            vertex_visit_stack.pop()

            vertex_status_list[current_vertex] = POPPED_OUT

            time += 1

            vertex_f_time[current_vertex] += time

    return None

def get_adj_vertices(vertex):

    index = int(vertex) - 1

    for j in range(vertex_num):

        if adj_matrix[index][j]:

            adj_matrix[index][j] = 0

            return j + 1

    return None

def dfs_start():

    global time

    for i in range(vertex_num):

        if vertex_status_list[i + 1] == UNVISITED:

            # print('round', i + 1)

            graph_dfs(v_init=i + 1)

            time += 1

if __name__ == '__main__':

    _input = sys.stdin.readlines()

    vertex_num = int(_input[0])

    vertex_info = list([x.split() for x in _input[1:]])

    init_adj_matrix = [[0] * vertex_num for _ in range(vertex_num)]

    # assert len(vertex_info) == vertex_num

    # config length = (vertex_num + 1)

    vertex_visit_stack = [-1]

    vertex_status_list = [UNVISITED] * vertex_num

    vertex_status_list.insert(0, -1)

    vertex_d_time, vertex_f_time = ([0] * (vertex_num + 1) for _ in range(2))

    adj_matrix = generate_adj_matrix(vertex_info)

    # timing start from 1

    time = 1

    dfs_start()

    for k in range(vertex_num):

        print((k + 1, vertex_d_time[k + 1], vertex_f_time[k + 1]))

#!/usr/bin/env python

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

import sys

UNVISITED, VISITED_IN_STACK, POPPED_OUT = 0, 1, 2

def generate_adj_matrix(v_info):

    for v_detail in v_info:

        v_adj_list = v_detail[2:]

        # assert len(v_adj_list) == int(v_detail[1])

        for each in v_adj_list:

            init_adj_matrix[int(v_detail[0]) - 1][int(each) - 1] = 1

    return init_adj_matrix

def graph_dfs(v_init):

    global time

    # init the first node of overall graph iterations(times >= 1)

    vertices_visit_stack.append(v_init)

    vertices_status_list[v_init] = VISITED_IN_STACK

    vertices_d_time[v_init] += time

    # init end

    while len(vertices_visit_stack) > 1:

        current_vertex = vertices_visit_stack[-1]

        next_vertex = get_adj_vertices(vertex=current_vertex)

        if next_vertex:

            if vertices_status_list[next_vertex] is UNVISITED:

                vertices_status_list[next_vertex] = VISITED_IN_STACK

                time += 1

                vertices_d_time[next_vertex] += time

                vertices_visit_stack.append(next_vertex)

        else:

            vertices_visit_stack.pop()

            vertices_status_list[current_vertex] = POPPED_OUT

            time += 1

            vertices_f_time[current_vertex] += time

    return None

def get_adj_vertices(vertex):

    index = int(vertex) - 1

    for j in range(vertices_num):

        if adj_matrix[index][j]:

            adj_matrix[index][j] = 0

            return j + 1

    return None

def dfs_start():

    global time

    for i in range(vertices_num):

        if vertices_status_list[i + 1] == UNVISITED:

            # print('round: ', i + 1)

            graph_dfs(v_init=i + 1)

            time += 1

if __name__ == '__main__':

    _input = sys.stdin.readlines()

    vertices_num = int(_input[0])

    vertices_info = list([x.split() for x in _input[1:]])

    init_adj_matrix = [[0] * vertices_num for _ in range(vertices_num)]

    # assert len(vertex_info) == vertex_num

    # config length = (vertex_num + 1)

    vertices_visit_stack = [-1]

    vertices_status_list = [UNVISITED] * vertices_num

    vertices_status_list.insert(0, -1)

    vertices_d_time, vertices_f_time = ([0] * (vertices_num + 1) for _ in range(2))

    adj_matrix = generate_adj_matrix(vertices_info)

    # timing start from 1

    time = 1

    dfs_start()

    for k in range(vertices_num):

        print((k + 1, vertices_d_time[k + 1], vertices_f_time[k + 1]))

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

UNVISITED, VISITED_IN_STACK, POPPED_OUT = 0, 1, 2

def generate_adj_matrix(v_info):
    for v_detail in v_info:
        v_adj_list = v_detail[2:]
        assert len(v_adj_list) == int(v_detail[1])
        for each in v_adj_list:
            init_adj_matrix[int(v_detail[0]) - 1][int(each) - 1] = 1
    return init_adj_matrix

def graph_dfs(v_init):
    global time
    # init the first node of overall graph iterations(times >= 1)
    vertex_visit_stack.append(v_init)
    vertex_status_list[v_init] = VISITED_IN_STACK
    vertex_d_time[v_init] += time
    # init end
    while len(vertex_visit_stack) > 1:
        current_vertex = vertex_visit_stack[-1]
        next_vertex = get_adj_vertices(vertex=current_vertex)
        if next_vertex:
            if vertex_status_list[next_vertex] is UNVISITED:
                vertex_status_list[next_vertex] = VISITED_IN_STACK
                time += 1
                vertex_d_time[next_vertex] += time
                vertex_visit_stack.append(next_vertex)
        else:
            vertex_visit_stack.pop()
            vertex_status_list[current_vertex] = POPPED_OUT
            time += 1
            vertex_f_time[current_vertex] += time
    return None

def get_adj_vertices(vertex):
    index = int(vertex) - 1
    for j in range(vertex_num):
        if adj_matrix[index][j]:
            adj_matrix[index][j] = 0
            return j + 1
    return None

def dfs_start():
    global time
    for i in range(vertex_num):
        if vertex_status_list[i + 1] == UNVISITED:
            # print('round', i + 1)
            graph_dfs(v_init=i + 1)
            time += 1

if __name__ == "__main__":
    _input = sys.stdin.readlines()
    vertex_num = int(_input[0])
    vertex_info = list([x.split() for x in _input[1:]])
    init_adj_matrix = [[0] * vertex_num for _ in range(vertex_num)]
    # assert len(vertex_info) == vertex_num
    # config length = (vertex_num + 1)
    vertex_visit_stack = [-1]
    vertex_status_list = [UNVISITED] * vertex_num
    vertex_status_list.insert(0, -1)
    vertex_d_time, vertex_f_time = ([0] * (vertex_num + 1) for _ in range(2))
    adj_matrix = generate_adj_matrix(vertex_info)
    # timing start from 1
    time = 1
    dfs_start()
    for k in range(vertex_num):
        print((k + 1, vertex_d_time[k + 1], vertex_f_time[k + 1]))

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

UNVISITED, VISITED_IN_STACK, POPPED_OUT = 0, 1, 2

def generate_adj_matrix(v_info):
    for v_detail in v_info:
        v_adj_list = v_detail[2:]
        # assert len(v_adj_list) == int(v_detail[1])
        for each in v_adj_list:
            init_adj_matrix[int(v_detail[0]) - 1][int(each) - 1] = 1
    return init_adj_matrix

def graph_dfs(v_init):
    global time
    # init the first node of overall graph iterations(times >= 1)
    vertices_visit_stack.append(v_init)
    vertices_status_list[v_init] = VISITED_IN_STACK
    vertices_d_time[v_init] += time
    # init end
    while len(vertices_visit_stack) > 1:
        current_vertex = vertices_visit_stack[-1]
        next_vertex = get_adj_vertices(vertex=current_vertex)
        if next_vertex:
            if vertices_status_list[next_vertex] is UNVISITED:
                vertices_status_list[next_vertex] = VISITED_IN_STACK
                time += 1
                vertices_d_time[next_vertex] += time
                vertices_visit_stack.append(next_vertex)
        else:
            vertices_visit_stack.pop()
            vertices_status_list[current_vertex] = POPPED_OUT
            time += 1
            vertices_f_time[current_vertex] += time
    return None

def get_adj_vertices(vertex):
    index = int(vertex) - 1
    for j in range(vertices_num):
        if adj_matrix[index][j]:
            adj_matrix[index][j] = 0
            return j + 1
    return None

def dfs_start():
    global time
    for i in range(vertices_num):
        if vertices_status_list[i + 1] == UNVISITED:
            # print('round: ', i + 1)
            graph_dfs(v_init=i + 1)
            time += 1

if __name__ == "__main__":
    _input = sys.stdin.readlines()
    vertices_num = int(_input[0])
    vertices_info = list([x.split() for x in _input[1:]])
    init_adj_matrix = [[0] * vertices_num for _ in range(vertices_num)]
    # assert len(vertex_info) == vertex_num
    # config length = (vertex_num + 1)
    vertices_visit_stack = [-1]
    vertices_status_list = [UNVISITED] * vertices_num
    vertices_status_list.insert(0, -1)
    vertices_d_time, vertices_f_time = ([0] * (vertices_num + 1) for _ in range(2))
    adj_matrix = generate_adj_matrix(vertices_info)
    # timing start from 1
    time = 1
    dfs_start()
    for k in range(vertices_num):
        print((k + 1, vertices_d_time[k + 1], vertices_f_time[k + 1]))

-        assert len(v_adj_list) == int(v_detail[1])

+        # assert len(v_adj_list) == int(v_detail[1])

-    vertex_status_list[v_init] = VISITED_IN_STACK

+    vertices_visit_stack.append(v_init)

+    vertices_status_list[v_init] = VISITED_IN_STACK

-        current_vertex = vertex_visit_stack[-1]

+    while len(vertices_visit_stack) > 1:

+        current_vertex = vertices_visit_stack[-1]

-            if vertex_status_list[next_vertex] is UNVISITED:

-                vertex_status_list[next_vertex] = VISITED_IN_STACK

+            if vertices_status_list[next_vertex] is UNVISITED:

+                vertices_status_list[next_vertex] = VISITED_IN_STACK

-                vertex_d_time[next_vertex] += time

-                vertex_visit_stack.append(next_vertex)

+                vertices_d_time[next_vertex] += time

+                vertices_visit_stack.append(next_vertex)

-            vertex_status_list[current_vertex] = POPPED_OUT

+            vertices_status_list[current_vertex] = POPPED_OUT

-            vertex_f_time[current_vertex] += time

+            vertices_f_time[current_vertex] += time

-        if vertex_status_list[i + 1] == UNVISITED:

+        if vertices_status_list[i + 1] == UNVISITED:

-    vertex_info = list([x.split() for x in _input[1:]])

-    init_adj_matrix = [[0] * vertex_num for _ in range(vertex_num)]

+    vertices_info = list([x.split() for x in _input[1:]])

+    init_adj_matrix = [[0] * vertices_num for _ in range(vertices_num)]

-    vertex_status_list = [UNVISITED] * vertex_num

-    vertex_d_time, vertex_f_time = ([0] * (vertex_num + 1) for _ in range(2))

-    adj_matrix = generate_adj_matrix(vertex_info)

+    vertices_status_list = [UNVISITED] * vertices_num

+    vertices_d_time, vertices_f_time = ([0] * (vertices_num + 1) for _ in range(2))

+    adj_matrix = generate_adj_matrix(vertices_info)

-        print((k + 1, vertex_d_time[k + 1], vertex_f_time[k + 1]))

+        print((k + 1, vertices_d_time[k + 1], vertices_f_time[k + 1]))


Input:
H,W=list(map(int, input().split()))

A=[list(eval(input())) for _ in range(H)]

#dp[i][j]=最も近い黒マスまでの最小マンハッタン距離

INF=10**9

dp = [[INF] * W for _ in range(H)]

#右

for i in range(H):

    c = INF

    for j in range(W):

        if A[i][j] == '#': c = 0

        elif j>=1: c = dp[i][j-1] + 1

        dp[i][j] = min(dp[i][j], c)

#下

for j in range(W):

    c = INF

    for i in range(H):

        if A[i][j] == '#': c = 0

        elif i>=1: c = dp[i-1][j] + 1

        dp[i][j] = min(dp[i][j], c)

#左

for i in range(H):

    c = INF

    for j in range(W-1,-1,-1):

        if A[i][j] == '#': c = 0

        elif j<W-1: c = dp[i][j+1] + 1

        dp[i][j] = min(dp[i][j], c)

#上

for j in range(W):

    c = INF

    for i in range(H-1,-1,-1):

        if A[i][j] == '#': c = 0

        elif i<H-1: c = dp[i+1][j] + 1

        dp[i][j] = min(dp[i][j], c)

ans=0

for i in range(H):

    for j in range(W):

        ans = max(ans, dp[i][j])

print(ans)

# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)

import sys

from collections import deque

def main(H, W, A):

    dist = [[-1] * W for _ in range(H)]

    q = deque()

    for i in range(H):

        for j in range(W):

            if A[i][j] == '#':

                dist[i][j] = 0

                q.append((i, j, 0))

    ans = 0

    while q:

        i, j, d = q.popleft()

        ans = max(ans, d)

        for ni, nj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:

            if not (0 <= ni < H and 0 <= nj < W): continue

            if dist[ni][nj] >= 0: continue

            dist[ni][nj] = d + 1

            q.append((ni, nj, d + 1))

    print(ans)

if __name__ == '__main__':

    input = sys.stdin.readline

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

    A = [input().rstrip() for _ in range(H)]

    main(H, W, A)

H, W = list(map(int, input().split()))
A = [list(eval(input())) for _ in range(H)]
# dp[i][j]=最も近い黒マスまでの最小マンハッタン距離
INF = 10**9
dp = [[INF] * W for _ in range(H)]
# 右
for i in range(H):
    c = INF
    for j in range(W):
        if A[i][j] == "#":
            c = 0
        elif j >= 1:
            c = dp[i][j - 1] + 1
        dp[i][j] = min(dp[i][j], c)
# 下
for j in range(W):
    c = INF
    for i in range(H):
        if A[i][j] == "#":
            c = 0
        elif i >= 1:
            c = dp[i - 1][j] + 1
        dp[i][j] = min(dp[i][j], c)
# 左
for i in range(H):
    c = INF
    for j in range(W - 1, -1, -1):
        if A[i][j] == "#":
            c = 0
        elif j < W - 1:
            c = dp[i][j + 1] + 1
        dp[i][j] = min(dp[i][j], c)
# 上
for j in range(W):
    c = INF
    for i in range(H - 1, -1, -1):
        if A[i][j] == "#":
            c = 0
        elif i < H - 1:
            c = dp[i + 1][j] + 1
        dp[i][j] = min(dp[i][j], c)
ans = 0
for i in range(H):
    for j in range(W):
        ans = max(ans, dp[i][j])
print(ans)

# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
from collections import deque

def main(H, W, A):
    dist = [[-1] * W for _ in range(H)]
    q = deque()
    for i in range(H):
        for j in range(W):
            if A[i][j] == "#":
                dist[i][j] = 0
                q.append((i, j, 0))
    ans = 0
    while q:
        i, j, d = q.popleft()
        ans = max(ans, d)
        for ni, nj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
            if not (0 <= ni < H and 0 <= nj < W):
                continue
            if dist[ni][nj] >= 0:
                continue
            dist[ni][nj] = d + 1
            q.append((ni, nj, d + 1))
    print(ans)

if __name__ == "__main__":
    input = sys.stdin.readline
    H, W = list(map(int, input().split()))
    A = [input().rstrip() for _ in range(H)]
    main(H, W, A)

-A = [list(eval(input())) for _ in range(H)]

-# dp[i][j]=最も近い黒マスまでの最小マンハッタン距離

+# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)

+    dist = [[-1] * W for _ in range(H)]

+            if not (0 <= ni < H and 0 <= nj < W):

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

+    A = [input().rstrip() for _ in range(H)]


Input:
def solve():

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

    h = [int(eval(input())) for _ in range(n)]

    h.sort()

    hk = [h[i+k-1] - h[i] for i in range(n - k + 1)]

    print((min(hk)))

if __name__ == '__main__':

    solve()

def solve():

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

    # h = [int(input()) for _ in range(n)]

    n, k, *h = list(map(int, open(0).read().split()))

    h.sort()

    hk = [h[i+k-1] - h[i] for i in range(n - k + 1)]

    print((min(hk)))

if __name__ == '__main__':

    solve()

def solve():
    n, k = list(map(int, input().split()))
    h = [int(eval(input())) for _ in range(n)]
    h.sort()
    hk = [h[i + k - 1] - h[i] for i in range(n - k + 1)]
    print((min(hk)))

if __name__ == "__main__":
    solve()

def solve():
    # n, k = map(int, input().split())
    # h = [int(input()) for _ in range(n)]
    n, k, *h = list(map(int, open(0).read().split()))
    h.sort()
    hk = [h[i + k - 1] - h[i] for i in range(n - k + 1)]
    print((min(hk)))

if __name__ == "__main__":
    solve()

-    n, k = list(map(int, input().split()))

-    h = [int(eval(input())) for _ in range(n)]

+    # h = [int(input()) for _ in range(n)]

+    n, k, *h = list(map(int, open(0).read().split()))


Input:
from itertools import combinations, chain
from functools import reduce

def eval_str(string):

    s = string.split("+")

    return int(reduce(lambda x,y: int(x)+int(y), s))

mystr = input()

allsubsets = lambda n: list(chain(*[combinations(list(range(1,n)), ni) for ni in range(n+1)]))

l = allsubsets(len(mystr))

#for i in xrange(len(l)):

#    l[i] = list(l[i])

mylist = []

#print l

for x in l:

    s = ""

    prev = 0

    for y in x:

        s += mystr[prev:int(y)]

        s += "+"

        prev = int(y)

    s += mystr[prev:]

    mylist.append(s)

#print mylist

tot = 0

for x in mylist:

    tot += eval_str(x)

print(tot)

def eval(d,mask):

    s = ''

    for i in range(len(mask)):

        s += d[i]

        if mask[i] == '1':

            s += '+'

    s += d[-1]

    l = s.split('+')

    res = sum(map(int,l))

    return res

d = list(input())

tot = 0

for i in range(2**(len(d)-1)):

    mask = bin(2**(len(d)-1)+i)[3:]

    tot += eval(d,mask)

print(tot)

from itertools import combinations, chain
from functools import reduce

def eval_str(string):
    s = string.split("+")
    return int(reduce(lambda x, y: int(x) + int(y), s))

mystr = input()
allsubsets = lambda n: list(
    chain(*[combinations(list(range(1, n)), ni) for ni in range(n + 1)])
)
l = allsubsets(len(mystr))
# for i in xrange(len(l)):
#    l[i] = list(l[i])
mylist = []
# print l
for x in l:
    s = ""
    prev = 0
    for y in x:
        s += mystr[prev : int(y)]
        s += "+"
        prev = int(y)
    s += mystr[prev:]
    mylist.append(s)
# print mylist
tot = 0
for x in mylist:
    tot += eval_str(x)
print(tot)

def eval(d, mask):
    s = ""
    for i in range(len(mask)):
        s += d[i]
        if mask[i] == "1":
            s += "+"
    s += d[-1]
    l = s.split("+")
    res = sum(map(int, l))
    return res

d = list(input())
tot = 0
for i in range(2 ** (len(d) - 1)):
    mask = bin(2 ** (len(d) - 1) + i)[3:]
    tot += eval(d, mask)
print(tot)

-from itertools import combinations, chain

-    return int(reduce(lambda x, y: int(x) + int(y), s))

-    chain(*[combinations(list(range(1, n)), ni) for ni in range(n + 1)])


Input:
N = int(eval(input()))

S = eval(input())

ans = 0

for n in range(1000):

    c = [n // 100, (n // 10) % 10, n % 10]

    f = 0

    for i in range(N):

        if S[i] == str(c[f]):

            f += 1

        if f == 3:

            break

    if f == 3:

        ans += 1

print(ans)

N = int(eval(input()))

S = eval(input())

ans = 0

for n in range(1000):

    target = "{:03}".format(n)

    j = 0

    for i in range(N):

        if S[i] == target[j]:

            j += 1

        if j == 3:

            ans += 1

            break

print(ans)


Input:
from collections import defaultdict

N = int(input())

counter = defaultdict(int)

for a in map(int, input().split()):

    if a % 4 == 0:

        counter[2] += 1

    elif a % 2 == 0:

        counter[1] += 1

    else:

        counter[0] += 1

if counter[1] == 0:

    print('Yes') if counter[0] <= counter[2] + 1 else print('No')

else:

    print('Yes') if counter[0] <= counter[2] else print('No')

from collections import Counter

N = int(input())

c = Counter(map(lambda x: int(x) % 4, input().split()))

print('Yes') if sum([c[1], c[2] > 0, c[3]]) <= c[0] + 1 else print('No')

from collections import defaultdict

N = int(input())
counter = defaultdict(int)
for a in map(int, input().split()):
    if a % 4 == 0:
        counter[2] += 1
    elif a % 2 == 0:
        counter[1] += 1
    else:
        counter[0] += 1
if counter[1] == 0:
    print("Yes") if counter[0] <= counter[2] + 1 else print("No")
else:
    print("Yes") if counter[0] <= counter[2] else print("No")

from collections import Counter

N = int(input())
c = Counter(map(lambda x: int(x) % 4, input().split()))
print("Yes") if sum([c[1], c[2] > 0, c[3]]) <= c[0] + 1 else print("No")

-    print("Yes") if counter[0] <= counter[2] + 1 else print("No")

-    print("Yes") if counter[0] <= counter[2] else print("No")

+c = Counter(map(lambda x: int(x) % 4, input().split()))


Input:
from collections import defaultdict,deque

import sys,heapq,bisect,math,itertools,string,queue

sys.setrecursionlimit(10**8)

INF = float('inf')

mod = 10**9+7

eps = 10**-7

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

def inpl_str(): return list(input().split())

S = eval(input())

bs = -1

for s in S:

    if s == bs:

        print('Bad')

        break

    bs = s

else:

    print('Good')

from collections import defaultdict,deque

import sys,heapq,bisect,math,itertools,string,queue

sys.setrecursionlimit(10**8)

INF = float('inf')

mod = 10**9+7

eps = 10**-7

def inp(): return int(eval(input()))

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

def inpl_str(): return list(input().split())

S = eval(input())

if S[0] == S[1] or S[1]==S[2] or S[2]==S[3]:

    print('Bad')

else:

    print('Good')

from collections import defaultdict, deque
import sys, heapq, bisect, math, itertools, string, queue

sys.setrecursionlimit(10**8)
INF = float("inf")
mod = 10**9 + 7
eps = 10**-7

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

def inpl_str():
    return list(input().split())

S = eval(input())
bs = -1
for s in S:
    if s == bs:
        print("Bad")
        break
    bs = s
else:
    print("Good")

from collections import defaultdict, deque
import sys, heapq, bisect, math, itertools, string, queue

sys.setrecursionlimit(10**8)
INF = float("inf")
mod = 10**9 + 7
eps = 10**-7

def inp():
    return int(eval(input()))

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

def inpl_str():
    return list(input().split())

S = eval(input())
if S[0] == S[1] or S[1] == S[2] or S[2] == S[3]:
    print("Bad")
else:
    print("Good")


Input:
import sys

sys.setrecursionlimit(1 << 25)

read = sys.stdin.readline

ra = range

enu = enumerate

def read_ints():

    return list(map(int, read().split()))

def read_a_int():

    return int(read())

def read_tuple(H):

    '''

    H is number of rows

    '''

    ret = []

    for _ in range(H):

        ret.append(tuple(map(int, read().split())))

    return ret

def read_col(H):

    '''

    H is number of rows

    A列、B列が与えられるようなとき

    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合

    '''

    ret = []

    for _ in range(H):

        ret.append(list(map(int, read().split())))

    return tuple(map(list, list(zip(*ret))))

def read_matrix(H):

    '''

    H is number of rows

    '''

    ret = []

    for _ in range(H):

        ret.append(list(map(int, read().split())))

    return ret

    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため

MOD = 10**9 + 7

INF = 2**31  # 2147483648 > 10**9

# default import

from collections import defaultdict, Counter, deque

from operator import itemgetter

from itertools import product, permutations, combinations

from bisect import bisect_left, bisect_right  # , insort_left, insort_right

# 全通り調べる問題

K, S = read_ints()

X = list(range(K + 1))  # Kは2500なのでK^2は間に合う

# X,Yについて全探索してZについて二分探索すればよい #連続なので範囲に入ってれば良い（二分探索もいらない！）

ans = 0

for x in X:

    for y in X:

        z = S - x - y

        if 0 <= z <= K:

            ans += 1

print(ans)

import sys

sys.setrecursionlimit(1 << 25)

readline = sys.stdin.buffer.readline

read = sys.stdin.readline  # 文字列読み込む時はこっち

ra = range

enu = enumerate

def exit(*argv, **kwarg):

    print(*argv, **kwarg)

    sys.exit()

def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))

# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと

def a_int(): return int(readline())

def ints(): return list(map(int, readline().split()))

def read_col(H):

    '''H is number of rows

    A列、B列が与えられるようなとき

    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''

    ret = []

    for _ in range(H):

        ret.append(list(map(int, readline().split())))

    return tuple(map(list, zip(*ret)))

def read_tuple(H):

    '''H is number of rows'''

    ret = []

    for _ in range(H):

        ret.append(tuple(map(int, readline().split())))

    return ret

def read_matrix(H):

    '''H is number of rows'''

    ret = []

    for _ in range(H):

        ret.append(list(map(int, readline().split())))

    return ret

    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため

MOD = 10**9 + 7

INF = 2**31  # 2147483648 > 10**9

# default import

from collections import defaultdict, Counter, deque

from operator import itemgetter, xor, add

from itertools import product, permutations, combinations

from bisect import bisect_left, bisect_right  # , insort_left, insort_right

from functools import reduce

from math import gcd

def lcm(a, b):

    # 最小公倍数

    g = gcd(a, b)

    return a // g * b

K, S = ints()

ans = 0

for x in range(K + 1):

    for y in range(K + 1):

        z = S - x - y

        if 0 <= z <= K:

            # print(x, y, z)

            ans += 1

print(ans)

import sys

sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate

def read_ints():
    return list(map(int, read().split()))

def read_a_int():
    return int(read())

def read_tuple(H):
    """
    H is number of rows
    """
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret

def read_col(H):
    """
    H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合
    """
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, list(zip(*ret))))

def read_matrix(H):
    """
    H is number of rows
    """
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため

MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right

# 全通り調べる問題
K, S = read_ints()
X = list(range(K + 1))  # Kは2500なのでK^2は間に合う
# X,Yについて全探索してZについて二分探索すればよい #連続なので範囲に入ってれば良い（二分探索もいらない！）
ans = 0
for x in X:
    for y in X:
        z = S - x - y
        if 0 <= z <= K:
            ans += 1
print(ans)

import sys

sys.setrecursionlimit(1 << 25)
readline = sys.stdin.buffer.readline
read = sys.stdin.readline  # 文字列読み込む時はこっち
ra = range
enu = enumerate

def exit(*argv, **kwarg):
    print(*argv, **kwarg)
    sys.exit()

def mina(*argv, sub=1):
    return list(map(lambda x: x - sub, argv))

# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと
def a_int():
    return int(readline())

def ints():
    return list(map(int, readline().split()))

def read_col(H):
    """H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合"""
    ret = []
    for _ in range(H):
        ret.append(list(map(int, readline().split())))
    return tuple(map(list, zip(*ret)))

def read_tuple(H):
    """H is number of rows"""
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, readline().split())))
    return ret

def read_matrix(H):
    """H is number of rows"""
    ret = []
    for _ in range(H):
        ret.append(list(map(int, readline().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため

MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter, xor, add
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from functools import reduce
from math import gcd

def lcm(a, b):
    # 最小公倍数
    g = gcd(a, b)
    return a // g * b

K, S = ints()
ans = 0
for x in range(K + 1):
    for y in range(K + 1):
        z = S - x - y
        if 0 <= z <= K:
            # print(x, y, z)
            ans += 1
print(ans)

+read = sys.stdin.readline  # 文字列読み込む時はこっち

-    return list(map(int, read().split()))

+    return list(map(lambda x: x - sub, argv))

+# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと

+    return list(map(int, readline().split()))

+    A列、B列が与えられるようなとき

+    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合"""

+        ret.append(list(map(int, readline().split())))

-        ret.append(tuple(map(int, read().split())))

+        ret.append(tuple(map(int, readline().split())))

-    A列、B列が与えられるようなとき

-    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合

-        ret.append(list(map(int, read().split())))

-    return tuple(map(list, list(zip(*ret))))

+from operator import itemgetter, xor, add

-X = list(range(K + 1))  # Kは2500なのでK^2は間に合う

-# X,Yについて全探索してZについて二分探索すればよい #連続なので範囲に入ってれば良い（二分探索もいらない！）

+    # 最小公倍数


Input:
N,W=list(map(int,input().split()))

w,v=[],[]

for i in range(N):

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

  w.append(a)

  v.append(b)

dp=[[0]*(W+1) for i in range(N+1)]

for i in range(N):

  for j in range(W+1):

      if j-w[i]>=0:

          dp[i+1][j]=dp[i][j-w[i]]+v[i]

      dp[i+1][j]=max(dp[i+1][j],dp[i][j])

print((dp[N][W]))

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

w,v=[],[]

for i in range(N):

  ww,vv=list(map(int,input().split()))

  w.append(ww)

  v.append(vv)

dp=[[0]*(W+1) for i in range(N+1)]

for i in range(N):

  for j in range(W+1):

    if j-w[i]>=0:

      dp[i+1][j]=max(dp[i][j-w[i]]+v[i],dp[i+1][j])

    dp[i+1][j]=max(dp[i+1][j],dp[i][j])

print((dp[-1][-1]))

N, W = list(map(int, input().split()))
w, v = [], []
for i in range(N):
    a, b = list(map(int, input().split()))
    w.append(a)
    v.append(b)
dp = [[0] * (W + 1) for i in range(N + 1)]
for i in range(N):
    for j in range(W + 1):
        if j - w[i] >= 0:
            dp[i + 1][j] = dp[i][j - w[i]] + v[i]
        dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
print((dp[N][W]))

N, W = list(map(int, input().split()))
w, v = [], []
for i in range(N):
    ww, vv = list(map(int, input().split()))
    w.append(ww)
    v.append(vv)
dp = [[0] * (W + 1) for i in range(N + 1)]
for i in range(N):
    for j in range(W + 1):
        if j - w[i] >= 0:
            dp[i + 1][j] = max(dp[i][j - w[i]] + v[i], dp[i + 1][j])
        dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
print((dp[-1][-1]))

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

+    ww, vv = list(map(int, input().split()))


Input:
n,k=list(map(int,input().split()))

D=set(list(map(int,input().split())))

for i in range(n,10*n):

    num=set(list(map(int,str(i))))

    if i>=n and len(D&num)==0:

        print(i)

        exit()

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

D=set(list(map(str,input().split())))

for i in range(n,10*n):

    num=set(list(str(i)))

    if i>=n and len(D&num)==0:

        print(i)

        exit()

n, k = list(map(int, input().split()))
D = set(list(map(int, input().split())))
for i in range(n, 10 * n):
    num = set(list(map(int, str(i))))
    if i >= n and len(D & num) == 0:
        print(i)
        exit()

n, k = list(map(int, input().split()))
D = set(list(map(str, input().split())))
for i in range(n, 10 * n):
    num = set(list(str(i)))
    if i >= n and len(D & num) == 0:
        print(i)
        exit()

-D = set(list(map(int, input().split())))

+D = set(list(map(str, input().split())))


Input:
import copy

def culc(array):

    summy = 0

    indexes = [i for i, x in enumerate(array) if x == '+']

    ff = 0

    for i in indexes:

        summy += int("".join(array[ff:i]))

        ff = i+1

    summy += int("".join(array[ff:]))

    return summy

nums = list(eval(input()))

ans = 0

for i in range(2**(len(nums)-1)):

    bit = bin(i)

    obj = copy.deepcopy(nums)

    k = 0

    for j in range(len(nums)-1):

        if ( i >> j) & 1:

            obj.insert(j+1+k,'+')

            k += 1

    ans += culc(obj)

print(ans)

S = list(eval(input()))

ans = 0

for i in range(2**(len(S)-1)):

    tmp = S

    p = list(bin(i))

    flag = ['0' for _ in range(len(S) - len(p) + 1)] + p[2:]

    nums = []

    l = 0

    for j in range(len(S)-1):

        if flag[j] == '1':

            nums.append("".join(tmp[l:j+1]))

            l = j+1

    nums.append("".join(tmp[l:]))

    for n in nums:

        ans += int(n)

print(ans)

import copy

def culc(array):
    summy = 0
    indexes = [i for i, x in enumerate(array) if x == "+"]
    ff = 0
    for i in indexes:
        summy += int("".join(array[ff:i]))
        ff = i + 1
    summy += int("".join(array[ff:]))
    return summy

nums = list(eval(input()))
ans = 0
for i in range(2 ** (len(nums) - 1)):
    bit = bin(i)
    obj = copy.deepcopy(nums)
    k = 0
    for j in range(len(nums) - 1):
        if (i >> j) & 1:
            obj.insert(j + 1 + k, "+")
            k += 1
    ans += culc(obj)
print(ans)

S = list(eval(input()))
ans = 0
for i in range(2 ** (len(S) - 1)):
    tmp = S
    p = list(bin(i))
    flag = ["0" for _ in range(len(S) - len(p) + 1)] + p[2:]
    nums = []
    l = 0
    for j in range(len(S) - 1):
        if flag[j] == "1":
            nums.append("".join(tmp[l : j + 1]))
            l = j + 1
    nums.append("".join(tmp[l:]))
    for n in nums:
        ans += int(n)
print(ans)

-    indexes = [i for i, x in enumerate(array) if x == "+"]

-        summy += int("".join(array[ff:i]))

+    flag = ["0" for _ in range(len(S) - len(p) + 1)] + p[2:]

+            nums.append("".join(tmp[l : j + 1]))


Input:
N = int(eval(input()))

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

def common_divisor(n):

    cd = []

    for i in range(1,int(n**0.5)+2):

        if n%i==0:

            cd.append(i)

            if i != n//i:

                cd.append(n//i)

    return set(cd)

#print(cd_dic)

cds = common_divisor(A[0]).union(common_divisor(A[1]))

ans = 1

for k in cds:

    #print(cd_dic)

    cnt = 0

    for a in A:

        if a%k!=0:

            cnt += 1

            if cnt == 2:

                break

    else:

        ans = max(ans,k)

print(ans)

class SegmentTree():

  def __init__(self, n, oper, e):

    self.n = n

    self.oper = oper

    self.e = e

    self.log = (n - 1).bit_length()

    self.size = 1 << self.log

    self.data = [e] * (2 * self.size)

  def update(self, k):

    self.data[k] = self.oper(self.data[2 * k], self.data[2 * k + 1])

  def build(self, arr):

    #assert len(arr) <= self.n

    for i in range(self.n):

      self.data[self.size + i] = arr[i]

    for i in range(self.size-1,0,-1):

      self.update(i)

  def set(self, p, x):

    #assert 0 <= p < self.n

    p += self.size

    self.data[p] = x

    for i in range(self.log):

      p >>= 1

      self.update(p)

  def get(self, p):

    #assert 0 <= p < self.n

    return self.data[p + self.size]

  def prod(self, l, r):

    #assert 0 <= l <= r <= self.n

    sml = smr = self.e

    l += self.size

    r += self.size

    while l < r:

      if l & 1:

        sml = self.oper(sml, self.data[l])

        l += 1

      if r & 1:

        r -= 1

        smr = self.oper(self.data[r], smr)

      l >>= 1

      r >>= 1

    return self.oper(sml, smr)

  def all_prod(self):

    return self.data[1]

  def max_right(self, l, f):

    #assert 0 <= l <= self.n

    #assert f(self.)

    if l == self.n: return self.n

    l += self.size

    sm = self.e

    while True:

      while l % 2 == 0: l >>= 1

      if not f(self.oper(sm, self.data[l])):

        while l < self.size:

          l = 2 * l

          if f(self.oper(sm, self.data[l])):

            sm = self.oper(sm, self.data[l])

            l += 1

        return l - self.size

      sm = self.oper(sm, self.data[l])

      l += 1

      if (l & -l) == l: break

    return self.n

  def min_left(self, r, f):

    #assert 0 <= r <= self.n

    #assert f(self.)

    if r == 0: return 0

    r += self.size

    sm = self.e

    while True:

      r -= 1

      while r > 1 and (r % 2): r >>= 1

      if not f(self.oper(self.data[r], sm)):

        while r < self.size:

          r = 2 * r + 1

          if f(self.oper(self.data[r], sm)):

            sm = self.oper(self.data[r], sm)

            r -= 1

        return r + 1 - self.size

      sm = self.oper(self.data[r], sm)

      if (r & -r) == r: break

    return 0

import sys

input = sys.stdin.readline

from math import gcd

e = 0

N = int(eval(input()))

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

st = SegmentTree(N,gcd,e)

st.build(A)

ans = max(st.prod(1,N),st.prod(0,N-1))

for i in range(1,N-1):

  ans = max(ans, gcd(st.prod(0,i),st.prod(i+1,N)))

print(ans)

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

def common_divisor(n):
    cd = []
    for i in range(1, int(n**0.5) + 2):
        if n % i == 0:
            cd.append(i)
            if i != n // i:
                cd.append(n // i)
    return set(cd)

# print(cd_dic)
cds = common_divisor(A[0]).union(common_divisor(A[1]))
ans = 1
for k in cds:
    # print(cd_dic)
    cnt = 0
    for a in A:
        if a % k != 0:
            cnt += 1
            if cnt == 2:
                break
    else:
        ans = max(ans, k)
print(ans)

class SegmentTree:
    def __init__(self, n, oper, e):
        self.n = n
        self.oper = oper
        self.e = e
        self.log = (n - 1).bit_length()
        self.size = 1 << self.log
        self.data = [e] * (2 * self.size)

    def update(self, k):
        self.data[k] = self.oper(self.data[2 * k], self.data[2 * k + 1])

    def build(self, arr):
        # assert len(arr) <= self.n
        for i in range(self.n):
            self.data[self.size + i] = arr[i]
        for i in range(self.size - 1, 0, -1):
            self.update(i)

    def set(self, p, x):
        # assert 0 <= p < self.n
        p += self.size
        self.data[p] = x
        for i in range(self.log):
            p >>= 1
            self.update(p)

    def get(self, p):
        # assert 0 <= p < self.n
        return self.data[p + self.size]

    def prod(self, l, r):
        # assert 0 <= l <= r <= self.n
        sml = smr = self.e
        l += self.size
        r += self.size
        while l < r:
            if l & 1:
                sml = self.oper(sml, self.data[l])
                l += 1
            if r & 1:
                r -= 1
                smr = self.oper(self.data[r], smr)
            l >>= 1
            r >>= 1
        return self.oper(sml, smr)

    def all_prod(self):
        return self.data[1]

    def max_right(self, l, f):
        # assert 0 <= l <= self.n
        # assert f(self.)
        if l == self.n:
            return self.n
        l += self.size
        sm = self.e
        while True:
            while l % 2 == 0:
                l >>= 1
            if not f(self.oper(sm, self.data[l])):
                while l < self.size:
                    l = 2 * l
                    if f(self.oper(sm, self.data[l])):
                        sm = self.oper(sm, self.data[l])
                        l += 1
                return l - self.size
            sm = self.oper(sm, self.data[l])
            l += 1
            if (l & -l) == l:
                break
        return self.n

    def min_left(self, r, f):
        # assert 0 <= r <= self.n
        # assert f(self.)
        if r == 0:
            return 0
        r += self.size
        sm = self.e
        while True:
            r -= 1
            while r > 1 and (r % 2):
                r >>= 1
            if not f(self.oper(self.data[r], sm)):
                while r < self.size:
                    r = 2 * r + 1
                    if f(self.oper(self.data[r], sm)):
                        sm = self.oper(self.data[r], sm)
                        r -= 1
                return r + 1 - self.size
            sm = self.oper(self.data[r], sm)
            if (r & -r) == r:
                break
        return 0

import sys

input = sys.stdin.readline
from math import gcd

e = 0
N = int(eval(input()))
A = list(map(int, input().split()))
st = SegmentTree(N, gcd, e)
st.build(A)
ans = max(st.prod(1, N), st.prod(0, N - 1))
for i in range(1, N - 1):
    ans = max(ans, gcd(st.prod(0, i), st.prod(i + 1, N)))
print(ans)

+        self.log = (n - 1).bit_length()

+        self.data = [e] * (2 * self.size)

+        self.data[k] = self.oper(self.data[2 * k], self.data[2 * k + 1])

+            self.data[self.size + i] = arr[i]

+        for i in range(self.size - 1, 0, -1):

+        return self.data[p + self.size]

+                sml = self.oper(sml, self.data[l])

+                smr = self.oper(self.data[r], smr)

+            if not f(self.oper(sm, self.data[l])):

+                    if f(self.oper(sm, self.data[l])):

+                        sm = self.oper(sm, self.data[l])

+            sm = self.oper(sm, self.data[l])

+            if not f(self.oper(self.data[r], sm)):

+                    if f(self.oper(self.data[r], sm)):

+                        sm = self.oper(self.data[r], sm)

+                return r + 1 - self.size

+            sm = self.oper(self.data[r], sm)

-    for i in range(1, int(n**0.5) + 2):

+ans = max(st.prod(1, N), st.prod(0, N - 1))

+    ans = max(ans, gcd(st.prod(0, i), st.prod(i + 1, N)))


Input:
# ABC084C - Snuke Festival

# Binary search

from bisect import bisect_left, bisect_right

n = int(eval(input()))

A, B, C = [sorted(list(map(int, input().rstrip().split()))) for _ in range(3)]

lgth = len(C)

ans = 0

for i in B:

    ans += bisect_left(A, i) * (lgth - bisect_right(C, i))

print(ans)

# ARC084C - Snuke Festival

from bisect import bisect_left, bisect_right

def main():

    n = int(eval(input()))

    A, B, C = [sorted(tuple(map(int, input().rstrip().split()))) for _ in range(3)]

    l, ans = len(C), 0

    for i in B:

        ans += bisect_left(A, i) * (l - bisect_right(C, i))

    print(ans)

if __name__ == "__main__":

    main()

-A, B, C = [sorted(list(map(int, input().rstrip().split()))) for _ in range(3)]

-    ans += bisect_left(A, i) * (lgth - bisect_right(C, i))

+    A, B, C = [sorted(tuple(map(int, input().rstrip().split()))) for _ in range(3)]

+        ans += bisect_left(A, i) * (l - bisect_right(C, i))


Input:
n = int(eval(input()))

a_list = [int(eval(input())) for _ in range(n)]

sorted_a_list = sorted(a_list)

max_num = sorted_a_list[-1]

second_max_num = sorted_a_list[-2]

result = [0]*n

for i in range(n):

    if a_list[i] == max_num:

        result[i] = second_max_num

    else:

        result[i] = max_num

for i in range(n):

    print((result[i]))

import sys

from collections import defaultdict

from heapq import *

sys.setrecursionlimit(10**8)

input = sys.stdin.readline

def main():

    """ main """

    N = int(eval(input()))

    AS = [int(eval(input())) for _ in range(N)]

    AS_dup = AS[:]

    AS.sort()

    for i in range(N):

        if AS_dup[i] == AS[-1]:

            print((AS[-2]))

        else:

            print((AS[-1]))

if __name__ == '__main__':

    main()

n = int(eval(input()))
a_list = [int(eval(input())) for _ in range(n)]
sorted_a_list = sorted(a_list)
max_num = sorted_a_list[-1]
second_max_num = sorted_a_list[-2]
result = [0] * n
for i in range(n):
    if a_list[i] == max_num:
        result[i] = second_max_num
    else:
        result[i] = max_num
for i in range(n):
    print((result[i]))

import sys
from collections import defaultdict
from heapq import *

sys.setrecursionlimit(10**8)
input = sys.stdin.readline

def main():
    """main"""
    N = int(eval(input()))
    AS = [int(eval(input())) for _ in range(N)]
    AS_dup = AS[:]
    AS.sort()
    for i in range(N):
        if AS_dup[i] == AS[-1]:
            print((AS[-2]))
        else:
            print((AS[-1]))

if __name__ == "__main__":
    main()

-a_list = [int(eval(input())) for _ in range(n)]

+    AS = [int(eval(input())) for _ in range(N)]


Input:
n=int(eval(input()))

l=sorted(list(map(int,input().split())))

m=min(l)

l2=[]

l3=[]

for i in range(1,int(m**(1/2)+1)):

  if m%i==0:

    l2.append(i)

    if i!=m//i:

      l2.append(m//i)

for i in l2:

  b=True

  for j in l:

    if j%i==0:

      pass

    else:

      b=False

  if b:

    l3.append(i)

print((max(l3)))

def gcd(n,m):

  a=min(n,m)

  b=max(n,m)

  while a!=0:

    b,a=a,b%a

  return b

n=int(eval(input()))

l=list(map(int,input().split()))

ans=l[0]

for i in range(1,n):

  ans=gcd(ans,l[i])

print(ans)

n = int(eval(input()))
l = sorted(list(map(int, input().split())))
m = min(l)
l2 = []
l3 = []
for i in range(1, int(m ** (1 / 2) + 1)):
    if m % i == 0:
        l2.append(i)
        if i != m // i:
            l2.append(m // i)
for i in l2:
    b = True
    for j in l:
        if j % i == 0:
            pass
        else:
            b = False
    if b:
        l3.append(i)
print((max(l3)))

def gcd(n, m):
    a = min(n, m)
    b = max(n, m)
    while a != 0:
        b, a = a, b % a
    return b

n = int(eval(input()))
l = list(map(int, input().split()))
ans = l[0]
for i in range(1, n):
    ans = gcd(ans, l[i])
print(ans)

-l = sorted(list(map(int, input().split())))


Input:
N = int(eval(input()))

A = (10**5+2)*[0]

for a in map(int,input().split()):

  A[a-1]+=1

  A[a]+=1

  A[a+1]+=1

print((max(A)))


Input:
N = int(eval(input()))

C = []

S = []

F = []

for i in range(N - 1):

    c, s, f = list(map(int, input().split()))

    C.append(c)

    S.append(s)

    F.append(f)

def next(s, t):

    # 始発

    if t < S[s]:

        t = S[s]

    # タイムラグ

    elif t % F[s]:

        t += F[s] - t % F[s]

    # 列車の移動時間

    t += C[s]

    return t

def main():

    # 出発駅

    for i in range(N - 1):

        t = next(i, 0)

        # 途中駅

        for j in range(i + 1, N - 1):

            t = next(j, t)

        print(t)

    print((0))

    return

main()

N = int(eval(input()))

CSFn = [[int(j) for j in input().split()] for i in range(N - 1)]

def next(s):

    t = 0

    for Ci, Si, Fi in CSFn[s:]:

        # 始発

        if t < Si:

            t = Si

        # タイムラグ

        elif t % Fi:

            t += Fi - t % Fi

        # 列車の移動時間

        t += Ci

    return t

def main():

    # 出発駅

    for i in range(N - 1):

        t = next(i)

        print(t)

    print((0))

    return

main()

-    c, s, f = list(map(int, input().split()))

+CSFn = [[int(j) for j in input().split()] for i in range(N - 1)]

-    # タイムラグ

-    # 列車の移動時間

+        # 始発

+        # タイムラグ

+        # 列車の移動時間

-        # 途中駅


Input:
import sys

input = sys.stdin.readline

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

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

dp = [[0 for _ in range(N+1)] for _ in range(T+1)]

# 重さwまで品物nまででで最大になる価値

prev = [[0 for _ in range(N+1)] for _ in range(T+1)]

for n in range(N): # 品物nまでの世界で決めていく

    a, b = AB[n]

    for w in range(T):

        if a > w: # カバンに入りきらないなら入れられない

            dp[w][n+1] = dp[w][n]

            prev[w][n+1] = w

        else: #カバンに入れられる可能性があるなら

            if b+dp[w-a][n] >= dp[w][n]:

                dp[w][n+1] = dp[w-a][n] + b

                prev[w][n+1] = w - a

            else:

                dp[w][n+1] = dp[w][n]

                prev[w][n+1] = w

ans = dp[T-1][N]

used = [False]*N

c = T-1

for i in reversed(list(range(N))):

    if prev[c][i+1] == c - AB[i][0]:

        used[i] = True

    c = prev[c][i+1]

p = 0

for i in range(N):

    if not used[i] and AB[i][1] > p:

        p = AB[i][1]

print((ans+p))

import sys

input = sys.stdin.readline

from operator import itemgetter

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

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

AB.sort(key=itemgetter(0))

dp = [[0 for _ in range(N+1)] for _ in range(T+1)]

# 重さwまで品物nまででで最大になる価値

C = []

for n in range(N): # 品物nまでの世界で決めていく

    a, b = AB[n]

    for w in range(T):

        if a > w: # カバンに入りきらないなら入れられない

            dp[w][n+1] = dp[w][n]

        else: #カバンに入れられる可能性があるなら

            if b+dp[w-a][n] >= dp[w][n]:

                dp[w][n+1] = dp[w-a][n] + b

            else:

                dp[w][n+1] = dp[w][n]

    C.append(dp[T-1][n]+b)

ans = max(C)

print(ans)

import sys

input = sys.stdin.readline
N, T = list(map(int, input().split()))
AB = [list(map(int, input().split())) for _ in range(N)]
dp = [[0 for _ in range(N + 1)] for _ in range(T + 1)]
# 重さwまで品物nまででで最大になる価値
prev = [[0 for _ in range(N + 1)] for _ in range(T + 1)]
for n in range(N):  # 品物nまでの世界で決めていく
    a, b = AB[n]
    for w in range(T):
        if a > w:  # カバンに入りきらないなら入れられない
            dp[w][n + 1] = dp[w][n]
            prev[w][n + 1] = w
        else:  # カバンに入れられる可能性があるなら
            if b + dp[w - a][n] >= dp[w][n]:
                dp[w][n + 1] = dp[w - a][n] + b
                prev[w][n + 1] = w - a
            else:
                dp[w][n + 1] = dp[w][n]
                prev[w][n + 1] = w
ans = dp[T - 1][N]
used = [False] * N
c = T - 1
for i in reversed(list(range(N))):
    if prev[c][i + 1] == c - AB[i][0]:
        used[i] = True
    c = prev[c][i + 1]
p = 0
for i in range(N):
    if not used[i] and AB[i][1] > p:
        p = AB[i][1]
print((ans + p))

import sys

input = sys.stdin.readline
from operator import itemgetter

N, T = list(map(int, input().split()))
AB = [list(map(int, input().split())) for _ in range(N)]
AB.sort(key=itemgetter(0))
dp = [[0 for _ in range(N + 1)] for _ in range(T + 1)]
# 重さwまで品物nまででで最大になる価値
C = []
for n in range(N):  # 品物nまでの世界で決めていく
    a, b = AB[n]
    for w in range(T):
        if a > w:  # カバンに入りきらないなら入れられない
            dp[w][n + 1] = dp[w][n]
        else:  # カバンに入れられる可能性があるなら
            if b + dp[w - a][n] >= dp[w][n]:
                dp[w][n + 1] = dp[w - a][n] + b
            else:
                dp[w][n + 1] = dp[w][n]
    C.append(dp[T - 1][n] + b)
ans = max(C)
print(ans)

-prev = [[0 for _ in range(N + 1)] for _ in range(T + 1)]


Input:
n,k,q,*a=list(map(int,open(0).read().split()))

s=sorted

m=1e9

for b in a:

    i=[i for i,t in enumerate(a)if t<b]

    l=s(sum([s(a[i+1:j])[::-1][k-1:]for i,j in zip([-1]+i,i+[n])],[]))

    if len(l)>=q:m=min(m,l[q-1]-b)

print(m)

def main():

    N, K, Q, *A = list(map(int, open(0).read().split()))

    ans = float("inf")

    for Y in set(A):

        C = []

        tmp = []

        for a in A:

            if a >= Y:

                tmp.append(a)

            else:

                if len(tmp) >= K:

                    C += sorted(tmp)[:len(tmp) - K + 1]

                tmp = []

        if len(tmp) >= K:

            C += sorted(tmp)[:len(tmp) - K + 1]

        if len(C) >= Q:

            C.sort()

            X = C[Q - 1]

            ans = min(ans, X - Y)

    print(ans)

main()

n, k, q, *a = list(map(int, open(0).read().split()))
s = sorted
m = 1e9
for b in a:
    i = [i for i, t in enumerate(a) if t < b]
    l = s(sum([s(a[i + 1 : j])[::-1][k - 1 :] for i, j in zip([-1] + i, i + [n])], []))
    if len(l) >= q:
        m = min(m, l[q - 1] - b)
print(m)

def main():
    N, K, Q, *A = list(map(int, open(0).read().split()))
    ans = float("inf")
    for Y in set(A):
        C = []
        tmp = []
        for a in A:
            if a >= Y:
                tmp.append(a)
            else:
                if len(tmp) >= K:
                    C += sorted(tmp)[: len(tmp) - K + 1]
                tmp = []
        if len(tmp) >= K:
            C += sorted(tmp)[: len(tmp) - K + 1]
        if len(C) >= Q:
            C.sort()
            X = C[Q - 1]
            ans = min(ans, X - Y)
    print(ans)

main()

-n, k, q, *a = list(map(int, open(0).read().split()))

-    i = [i for i, t in enumerate(a) if t < b]

+    N, K, Q, *A = list(map(int, open(0).read().split()))

+                    C += sorted(tmp)[: len(tmp) - K + 1]

+            C += sorted(tmp)[: len(tmp) - K + 1]


Input:
A = int(eval(input()))

B = int(eval(input()))

C = int(eval(input()))

X = int(eval(input()))

cnt = 0

for a in range(A+1):

    for b in range(B+1):

        for c in range(C+1):

            if (a*500 + b*100 + c*50) == X:

                cnt+=1

print(cnt)

A = int(eval(input()))

B = int(eval(input()))

C = int(eval(input()))

X = int(eval(input()))

cnt = 0

for a in range(min([A,-(-X//500)])+1):

    _a = a*500

    for b in range(min([B,-(-X//100)])+1):

        _b = b*100 + _a

        if _b > X: break

        for c in range(min([C,-(-X//50)])+1):

            _c = c*50 + _b

            if _c > X: break

            if _c == X:

                cnt+=1

print(cnt)

A = int(eval(input()))
B = int(eval(input()))
C = int(eval(input()))
X = int(eval(input()))
cnt = 0
for a in range(A + 1):
    for b in range(B + 1):
        for c in range(C + 1):
            if (a * 500 + b * 100 + c * 50) == X:
                cnt += 1
print(cnt)

A = int(eval(input()))
B = int(eval(input()))
C = int(eval(input()))
X = int(eval(input()))
cnt = 0
for a in range(min([A, -(-X // 500)]) + 1):
    _a = a * 500
    for b in range(min([B, -(-X // 100)]) + 1):
        _b = b * 100 + _a
        if _b > X:
            break
        for c in range(min([C, -(-X // 50)]) + 1):
            _c = c * 50 + _b
            if _c > X:
                break
            if _c == X:
                cnt += 1
print(cnt)


Input:
from bisect import *

if __name__ == '__main__':

    N = int(eval(input()))

    L = sorted(map(int, input().split()))

    print((sum(jdx - bisect(L, a - L[jdx], 0, jdx) for idx, a in enumerate(L) for jdx in range(idx))))

if __name__ == '__main__':

    N = int(eval(input()))

    L = sorted(map(int, input().split()))

    ret = 0

    for adx in range(N):

        cdx = adx

        for bdx in range(adx + 1, N):

            while cdx < N and L[cdx] < L[bdx] + L[adx]: cdx += 1

            ret += cdx - (bdx + 1)

    print(ret)

from bisect import *

if __name__ == "__main__":
    N = int(eval(input()))
    L = sorted(map(int, input().split()))
    print(
        (
            sum(
                jdx - bisect(L, a - L[jdx], 0, jdx)
                for idx, a in enumerate(L)
                for jdx in range(idx)
            )
        )
    )

if __name__ == "__main__":
    N = int(eval(input()))
    L = sorted(map(int, input().split()))
    ret = 0
    for adx in range(N):
        cdx = adx
        for bdx in range(adx + 1, N):
            while cdx < N and L[cdx] < L[bdx] + L[adx]:
                cdx += 1
            ret += cdx - (bdx + 1)
    print(ret)

-                jdx - bisect(L, a - L[jdx], 0, jdx)

-                for idx, a in enumerate(L)

+            while cdx < N and L[cdx] < L[bdx] + L[adx]:


Input:
S=eval(input())

S = S.replace('eraser', '')

S = S.replace('erase', '')

S = S.replace('dreamer', '')

S = S.replace('dream', '')

S=len(S)

if S==0:

    print('YES')

else:

    print('NO')

import re

s=eval(input())

s=re.sub('eraser','',s)

s=re.sub('erase','',s)

s=re.sub('dreamer','',s)

s=re.sub('dream','',s)

if s=='':

    print('YES')

else:

    print('NO')

S = eval(input())
S = S.replace("eraser", "")
S = S.replace("erase", "")
S = S.replace("dreamer", "")
S = S.replace("dream", "")
S = len(S)
if S == 0:
    print("YES")
else:
    print("NO")

import re

s = eval(input())
s = re.sub("eraser", "", s)
s = re.sub("erase", "", s)
s = re.sub("dreamer", "", s)
s = re.sub("dream", "", s)
if s == "":
    print("YES")
else:
    print("NO")

-S = eval(input())
-S = S.replace("eraser", "")
-S = S.replace("erase", "")
-S = S.replace("dreamer", "")
-S = S.replace("dream", "")
-S = len(S)
-if S == 0:
+import re
+
+s = eval(input())
+s = re.sub("eraser", "", s)
+s = re.sub("erase", "", s)
+s = re.sub("dreamer", "", s)
+s = re.sub("dream", "", s)
+if s == "":


a, b = list(map(int, open(0)))
print((a ^ b))

-a, b = list(map(int, open(0)))
-print((a ^ b))
+print((6 - sum(map(int, open(0)))))


Input:
from collections import Counter

n = int(eval(input()))

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

a_counter = Counter(a)

a_counter_li = list(a_counter)

if sum(a) == 0:

    print("Yes")

elif len(a)%3 != 0:

    print("No")

elif len(a_counter) > 3 or len(a_counter) <= 1:

    print("No")

elif len(a_counter) == 3:

    if a_counter[a_counter_li[0]] == n // 3 and a_counter[a_counter_li[1]] == n // 3 and a_counter[a_counter_li[2]] == n // 3:

        if a_counter_li[0]^a_counter_li[1]^a_counter_li[2] == 0:

            print("Yes")

        else:

            print('No')

    else:

        print("No")

else:

    a_counter_li.sort()

    if a_counter_li[0] == 0 and a_counter[a_counter_li[0]] == n // 3:

        print("Yes")

    else:

        print("No")

from collections import Counter

n = int(eval(input()))

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

a_counter = Counter(a)

k = list(a_counter.keys())

v = list(a_counter.values())

if len(a_counter) == 3 and k[0]^k[1]^k[2] == 0 and v[0] == v[1] == v[2]:

    print("Yes")

elif len(a_counter) == 2 and 0 in k and (v[0] == v[1]*2 or v[1] == v[0]*2):

    print("Yes")

elif len(a_counter) == 1 and 0 in k:

    print("Yes")

else:

    print("No")

from collections import Counter

n = int(eval(input()))
a = list(map(int, input().split()))
a_counter = Counter(a)
a_counter_li = list(a_counter)
if sum(a) == 0:
    print("Yes")
elif len(a) % 3 != 0:
    print("No")
elif len(a_counter) > 3 or len(a_counter) <= 1:
    print("No")
elif len(a_counter) == 3:
    if (
        a_counter[a_counter_li[0]] == n // 3
        and a_counter[a_counter_li[1]] == n // 3
        and a_counter[a_counter_li[2]] == n // 3
    ):
        if a_counter_li[0] ^ a_counter_li[1] ^ a_counter_li[2] == 0:
            print("Yes")
        else:
            print("No")
    else:
        print("No")
else:
    a_counter_li.sort()
    if a_counter_li[0] == 0 and a_counter[a_counter_li[0]] == n // 3:
        print("Yes")
    else:
        print("No")

from collections import Counter

n = int(eval(input()))
a = list(map(int, input().split()))
a_counter = Counter(a)
k = list(a_counter.keys())
v = list(a_counter.values())
if len(a_counter) == 3 and k[0] ^ k[1] ^ k[2] == 0 and v[0] == v[1] == v[2]:
    print("Yes")
elif len(a_counter) == 2 and 0 in k and (v[0] == v[1] * 2 or v[1] == v[0] * 2):
    print("Yes")
elif len(a_counter) == 1 and 0 in k:
    print("Yes")
else:
    print("No")

-elif len(a_counter) > 3 or len(a_counter) <= 1:

-        a_counter[a_counter_li[0]] == n // 3

-        and a_counter[a_counter_li[1]] == n // 3

-        and a_counter[a_counter_li[2]] == n // 3

-        if a_counter_li[0] ^ a_counter_li[1] ^ a_counter_li[2] == 0:

-    if a_counter_li[0] == 0 and a_counter[a_counter_li[0]] == n // 3:


Input:
s=eval(input())

if(s[0]==s[1])or(s[1]==s[2])or(s[2]==s[3]):

  print("Bad")

else: print("Good")

def main():

  s=eval(input())

  if(s[0]==s[1])or(s[1]==s[2])or(s[2]==s[3]):

    print("Bad")

  else: print("Good")

if __name__=="__main__": main()

def main():
    s = eval(input())
    if (s[0] == s[1]) or (s[1] == s[2]) or (s[2] == s[3]):
        print("Bad")
    else:
        print("Good")

if __name__ == "__main__":
    main()


Input:
s = eval(input())

if s[2] == s[3] and s[4] == s[5]:

    print('Yes')

else:

    print('No')

def main():

    s = eval(input())

    if s[2] == s[3] and s[4] == s[5]:

        print('Yes')

    else:

        print('No')

if __name__ == '__main__':

    main()

def main():
    s = eval(input())
    if s[2] == s[3] and s[4] == s[5]:
        print("Yes")
    else:
        print("No")

if __name__ == "__main__":
    main()

-s = eval(input())
-if s[2] == s[3] and s[4] == s[5]:
-    print("Yes")
-else:
-    print("No")
+def main():
+    s = eval(input())
+    if s[2] == s[3] and s[4] == s[5]:
+        print("Yes")
+    else:
+        print("No")
+
+
+if __name__ == "__main__":
+    main()


Input:
N = int(eval(input()))

count = 0

if N<105:

    print((0))

else:

    for i in range(105,N+1):

        yaku = 0

        if i%2 == 1:

            for j in range(1,i+1):

                if i%j == 0:

                    yaku += 1

            if yaku == 8:

                count += 1

    print(count)

N = int(eval(input()))

count = 0

for i in range(1,N+1):

    yaku = 0

    if i%2 == 1:

        for j in range(1,i+1):

            if i%j == 0:

                yaku += 1

        if yaku == 8:

            count += 1

print(count)

N = int(eval(input()))
count = 0
if N < 105:
    print((0))
else:
    for i in range(105, N + 1):
        yaku = 0
        if i % 2 == 1:
            for j in range(1, i + 1):
                if i % j == 0:
                    yaku += 1
            if yaku == 8:
                count += 1
    print(count)

N = int(eval(input()))
count = 0
for i in range(1, N + 1):
    yaku = 0
    if i % 2 == 1:
        for j in range(1, i + 1):
            if i % j == 0:
                yaku += 1
        if yaku == 8:
            count += 1
print(count)

-if N < 105:
-    print((0))
-else:
-    for i in range(105, N + 1):
-        yaku = 0
-        if i % 2 == 1:
-            for j in range(1, i + 1):
-                if i % j == 0:
-                    yaku += 1
-            if yaku == 8:
-                count += 1
-    print(count)
+for i in range(1, N + 1):
+    yaku = 0
+    if i % 2 == 1:
+        for j in range(1, i + 1):
+            if i % j == 0:
+                yaku += 1
+        if yaku == 8:
+            count += 1
+print(count)


Input:
n,m=list(map(int,input().split()))

#Union-Find

par=[-1 for i in range(n)]

def root(a):

    if par[a]<0:

        return a

    else:

        return root(par[a])

def size(a):

    return -par[root(a)]

def connect(a,b):

    a=root(a)

    b=root(b)

    if a==b:

        return False

    if size(a)<size(b):

        a,b=b,a

    par[a]+=par[b]

    par[b]=a

    return True

xyz=[]

for i in range(m):

    a=[int(j) for j in input().split()]

    xyz.append([a[0]-1,a[1]-1,a[2]%2])

    if root(a[0]-1)!=root(a[1]-1):

        connect(a[0]-1,a[1]-1)

ans=0

for i in range(n):

    ans+=1/size(i)

print((round(ans)))

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

#Union-Find

par=[-1 for i in range(n)]

def root(a):

    if par[a]<0:

        return a

    else:

        return root(par[a])

def size(a):

    return -par[root(a)]

def connect(a,b):

    a=root(a)

    b=root(b)

    if a==b:

        return False

    if size(a)<size(b):

        a,b=b,a

    par[a]+=par[b]

    par[b]=a

    return True

xyz=[]

for i in range(m):

    a=[int(j) for j in input().split()]

    xyz.append([a[0]-1,a[1]-1,a[2]%2])

    if root(a[0]-1)!=root(a[1]-1):

        connect(a[0]-1,a[1]-1)

ans=0

for i in range(n):

    if par[i]<0:

        ans+=1

print(ans)

n, m = list(map(int, input().split()))
# Union-Find
par = [-1 for i in range(n)]

def root(a):
    if par[a] < 0:
        return a
    else:
        return root(par[a])

def size(a):
    return -par[root(a)]

def connect(a, b):
    a = root(a)
    b = root(b)
    if a == b:
        return False
    if size(a) < size(b):
        a, b = b, a
    par[a] += par[b]
    par[b] = a
    return True

xyz = []
for i in range(m):
    a = [int(j) for j in input().split()]
    xyz.append([a[0] - 1, a[1] - 1, a[2] % 2])
    if root(a[0] - 1) != root(a[1] - 1):
        connect(a[0] - 1, a[1] - 1)
ans = 0
for i in range(n):
    ans += 1 / size(i)
print((round(ans)))

n, m = list(map(int, input().split()))
# Union-Find
par = [-1 for i in range(n)]

def root(a):
    if par[a] < 0:
        return a
    else:
        return root(par[a])

def size(a):
    return -par[root(a)]

def connect(a, b):
    a = root(a)
    b = root(b)
    if a == b:
        return False
    if size(a) < size(b):
        a, b = b, a
    par[a] += par[b]
    par[b] = a
    return True

xyz = []
for i in range(m):
    a = [int(j) for j in input().split()]
    xyz.append([a[0] - 1, a[1] - 1, a[2] % 2])
    if root(a[0] - 1) != root(a[1] - 1):
        connect(a[0] - 1, a[1] - 1)
ans = 0
for i in range(n):
    if par[i] < 0:
        ans += 1
print(ans)

-    ans += 1 / size(i)
-print((round(ans)))
+    if par[i] < 0:
+        ans += 1
+print(ans)


Input:
## coding: UTF-8

from decimal import *

s = input().split()

t = [int(p) for p in s]

#print(t)

if(t[0] == 1 or t[1] == 1):

    answer = 1

elif( Decimal(Decimal(t[0]) % 2 )== 1 and Decimal(Decimal(t[1]) % 2) == 1):

    n = Decimal( Decimal(Decimal(t[0]) - 1) // 2  )

    #print(n)

    m = Decimal( Decimal(Decimal(t[1]) - 1) // 2  )

    answer = Decimal(    Decimal(  Decimal(Decimal(m) + 1)     *    Decimal(Decimal(n) + 1)  )   + Decimal( Decimal(m) * Decimal(n) )       )

else:

    answer = Decimal(   Decimal(Decimal(t[0]) * Decimal(t[1])) // 2  )

print((int(answer)))

'''

H = t[0]

W = t[1]

ans = 0

if( W % 2 == 0):

    for i in range(H):

        ans += W / 2

else:

    for i in range(H):

        if(i % 2 == 0):

            ans += W / 2.0 + 0.5

        else:

            ans += W / 2.0 - 0.5

print(int(ans))

'''

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

if(H == 1 or W == 1):

    ans = 1

else:

    if(H*W%2 != 0):

        ans = H*W//2 + 1

    else:

        ans = H*W//2

print(ans)

## coding: UTF-8
from decimal import *

s = input().split()
t = [int(p) for p in s]
# print(t)
if t[0] == 1 or t[1] == 1:
    answer = 1
elif Decimal(Decimal(t[0]) % 2) == 1 and Decimal(Decimal(t[1]) % 2) == 1:
    n = Decimal(Decimal(Decimal(t[0]) - 1) // 2)
    # print(n)
    m = Decimal(Decimal(Decimal(t[1]) - 1) // 2)
    answer = Decimal(
        Decimal(Decimal(Decimal(m) + 1) * Decimal(Decimal(n) + 1))
        + Decimal(Decimal(m) * Decimal(n))
    )
else:
    answer = Decimal(Decimal(Decimal(t[0]) * Decimal(t[1])) // 2)
print((int(answer)))
"""
H = t[0]
W = t[1]
ans = 0
if( W % 2 == 0):
    for i in range(H):
        ans += W / 2
else:
    for i in range(H):
        if(i % 2 == 0):
            ans += W / 2.0 + 0.5
        else:
            ans += W / 2.0 - 0.5
print(int(ans))
"""

H, W = list(map(int, input().split()))
if H == 1 or W == 1:
    ans = 1
else:
    if H * W % 2 != 0:
        ans = H * W // 2 + 1
    else:
        ans = H * W // 2
print(ans)

-elif Decimal(Decimal(t[0]) % 2) == 1 and Decimal(Decimal(t[1]) % 2) == 1:

-    n = Decimal(Decimal(Decimal(t[0]) - 1) // 2)

-    m = Decimal(Decimal(Decimal(t[1]) - 1) // 2)

-        Decimal(Decimal(Decimal(m) + 1) * Decimal(Decimal(n) + 1))

-        + Decimal(Decimal(m) * Decimal(n))

-    answer = Decimal(Decimal(Decimal(t[0]) * Decimal(t[1])) // 2)


Input:
import sys

def sieve(m):

    N=list(range(1,m+2,2))

    r=int(m**.5)

    h=len(N)

    N[0]=0

    for i in range(h):

        x=N[i]

        if x>r: break

        if x and i+x<h: N[i+x:h:x]=[0] * ((h-1-i-x)/x+1)

    return N

def f0056(n):

    x=0

    if n<4 : x=0

    elif n==4: x=1

    elif n%2==1:

        if SIEVES[(n-2)/2]!=0:

            x=1

    else:

        a=n/2

        for e in PRIMES:

            if e>a:break

            if SIEVES[(n-e)/2]!=0:

                x+=1

    return x

SIEVES=sieve(50000)

PRIMES=[_f for _f in SIEVES if _f]

for n in sys.stdin:

    n=int(n)

    if n==0: break

    print(f0056(n))

import sys

def sieve(m):

    N=list(range(1,m+2,2))

    r=int(m**.5)

    h=len(N)

    N[0]=0

    for i in range(h):

        x=N[i]

        if x>r: break

        if x and i+x<h: N[i+x:h:x]=[0]*((h-1-i-x)/x+1)

    return N

def f0056(n):

    x=0

    if n<4:x=0

    elif n==4:x=1

    elif n%2==1:

        if S[(n-2)/2]:

            x=1

    else:

        a=n/2

        for e in PRIMES:

            if e>a: break

            if S[(n-e)/2]:

                x+=1

    return x

S=sieve(50000)

PRIMES=[_f for _f in S if _f]

for n in sys.stdin:

    n=int(n)

    if n==0: break

    print(f0056(n))

import sys

def sieve(m):
    N = list(range(1, m + 2, 2))
    r = int(m**0.5)
    h = len(N)
    N[0] = 0
    for i in range(h):
        x = N[i]
        if x > r:
            break
        if x and i + x < h:
            N[i + x : h : x] = [0] * ((h - 1 - i - x) / x + 1)
    return N

def f0056(n):
    x = 0
    if n < 4:
        x = 0
    elif n == 4:
        x = 1
    elif n % 2 == 1:
        if SIEVES[(n - 2) / 2] != 0:
            x = 1
    else:
        a = n / 2
        for e in PRIMES:
            if e > a:
                break
            if SIEVES[(n - e) / 2] != 0:
                x += 1
    return x

SIEVES = sieve(50000)
PRIMES = [_f for _f in SIEVES if _f]
for n in sys.stdin:
    n = int(n)
    if n == 0:
        break
    print(f0056(n))

import sys

def sieve(m):
    N = list(range(1, m + 2, 2))
    r = int(m**0.5)
    h = len(N)
    N[0] = 0
    for i in range(h):
        x = N[i]
        if x > r:
            break
        if x and i + x < h:
            N[i + x : h : x] = [0] * ((h - 1 - i - x) / x + 1)
    return N

def f0056(n):
    x = 0
    if n < 4:
        x = 0
    elif n == 4:
        x = 1
    elif n % 2 == 1:
        if S[(n - 2) / 2]:
            x = 1
    else:
        a = n / 2
        for e in PRIMES:
            if e > a:
                break
            if S[(n - e) / 2]:
                x += 1
    return x

S = sieve(50000)
PRIMES = [_f for _f in S if _f]
for n in sys.stdin:
    n = int(n)
    if n == 0:
        break
    print(f0056(n))


Input:
# D - Lunlun Number

K = int(eval(input()))

stack = [1, 2, 3, 4, 5, 6, 7, 8, 9]

i = 0

while len(stack) < K:

    first = int(str(stack[i])[-1:])

    if first == 0:

        stack.append(int(str(stack[i]) + str(first)))

        stack.append(int(str(stack[i]) + str(first + 1)))

    elif first == 9:

        stack.append(int(str(stack[i]) + str(first - 1)))

        stack.append(int(str(stack[i]) + str(first)))

    else:

        stack.append(int(str(stack[i]) + str(first - 1)))

        stack.append(int(str(stack[i]) + str(first)))

        stack.append(int(str(stack[i]) + str(first + 1)))

    i += 1

print((stack[K - 1]))

-        stack.append(int(str(stack[i]) + str(first)))

-        stack.append(int(str(stack[i]) + str(first + 1)))

-        stack.append(int(str(stack[i]) + str(first - 1)))


Input:
class uf_tree:

    def __init__(self, n):

        self._size = n

        self.sizes = [1] * n

        self.par = list(range(n))

    def find(self, x):

        if x == self.par[x]:

            return x

        self.par[x] = self.find(self.par[x])

        return self.par[x]

    def unite(self, x, y):

        self._size -= 1

        x, y = self.find(x), self.find(y)

        if x == y:

            return

        if self.sizes[x] < self.sizes[y]:

            x, y = y, x

        self.par[y] = x

        self.sizes[x] += self.sizes[y]

    def same(self, x, y):

        return self.find(x) == self.find(y)

    def size(self, x):

        return self.sizes[self.find(x)]

def com(x):

    return x*(x-1)//2

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

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

ans = []

benri = 0

uf = uf_tree(n+1)

benri = 0

for a, b in AB[::-1]:

    ans += [ com(n) - benri ]

    if uf.same(a, b):

        continue

    a_benri = com(uf.size(a) )

    b_benri = com(uf.size(b) )

    uf.unite(a, b)

    sum_benri = com( uf.size(a) )

    benri += sum_benri - a_benri - b_benri

print (*ans[::-1], sep="\n")

import sys

input = sys.stdin.readline

class uf_tree:

    def __init__(self, n):

        self._size = n

        self.sizes = [1] * n

        self.par = list(range(n))

    def find(self, x):

        if x == self.par[x]:

            return x

        self.par[x] = self.find(self.par[x])

        return self.par[x]

    def unite(self, x, y):

        self._size -= 1

        x, y = self.find(x), self.find(y)

        if x == y:

            return

        if self.sizes[x] < self.sizes[y]:

            x, y = y, x

        self.par[y] = x

        self.sizes[x] += self.sizes[y]

    def same(self, x, y):

        return self.find(x) == self.find(y)

    def size(self, x):

        return self.sizes[self.find(x)]

def com(x):

    return x*(x-1)//2

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

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

ans = []

benri = 0

uf = uf_tree(n+1)

for a, b in AB[::-1]:

    ans += [ com(n) - benri ]

    if uf.same(a, b):

        continue

    a_benri = com(uf.size(a) )

    b_benri = com(uf.size(b) )

    uf.unite(a, b)

    sum_benri = com( uf.size(a) )

    benri += sum_benri - a_benri - b_benri

print (*ans[::-1], sep="\n")

class uf_tree:
    def __init__(self, n):
        self._size = n
        self.sizes = [1] * n
        self.par = list(range(n))

    def find(self, x):
        if x == self.par[x]:
            return x
        self.par[x] = self.find(self.par[x])
        return self.par[x]

    def unite(self, x, y):
        self._size -= 1
        x, y = self.find(x), self.find(y)
        if x == y:
            return
        if self.sizes[x] < self.sizes[y]:
            x, y = y, x
        self.par[y] = x
        self.sizes[x] += self.sizes[y]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def size(self, x):
        return self.sizes[self.find(x)]

def com(x):
    return x * (x - 1) // 2

n, m = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(m)]
ans = []
benri = 0
uf = uf_tree(n + 1)
benri = 0
for a, b in AB[::-1]:
    ans += [com(n) - benri]
    if uf.same(a, b):
        continue
    a_benri = com(uf.size(a))
    b_benri = com(uf.size(b))
    uf.unite(a, b)
    sum_benri = com(uf.size(a))
    benri += sum_benri - a_benri - b_benri
print(*ans[::-1], sep="\n")

import sys

input = sys.stdin.readline

class uf_tree:
    def __init__(self, n):
        self._size = n
        self.sizes = [1] * n
        self.par = list(range(n))

    def find(self, x):
        if x == self.par[x]:
            return x
        self.par[x] = self.find(self.par[x])
        return self.par[x]

    def unite(self, x, y):
        self._size -= 1
        x, y = self.find(x), self.find(y)
        if x == y:
            return
        if self.sizes[x] < self.sizes[y]:
            x, y = y, x
        self.par[y] = x
        self.sizes[x] += self.sizes[y]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def size(self, x):
        return self.sizes[self.find(x)]

def com(x):
    return x * (x - 1) // 2

n, m = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(m)]
ans = []
benri = 0
uf = uf_tree(n + 1)
for a, b in AB[::-1]:
    ans += [com(n) - benri]
    if uf.same(a, b):
        continue
    a_benri = com(uf.size(a))
    b_benri = com(uf.size(b))
    uf.unite(a, b)
    sum_benri = com(uf.size(a))
    benri += sum_benri - a_benri - b_benri
print(*ans[::-1], sep="\n")

+import sys
+
+input = sys.stdin.readline
+
+
-benri = 0


Input:
X = int(eval(input()))

a = 1

while X >= a**2:

    a += 1

print((int((a-1)**2)))

X = int(eval(input()))

print((int((X**.5))**2))

X = int(eval(input()))
a = 1
while X >= a**2:
    a += 1
print((int((a - 1) ** 2)))


Input:
n = int(eval(input()))

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

q = int(eval(input()))

total = sum(A)

l = [[i, 0] for i in range(10**5+1)]

for _ in range(n):

    l[A[_]][1] += 1

for i in range(q):

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

    total -= (l[b][0] * l[b][1])

    total += (l[c][0] * l[b][1])

    print(total)

    l[c][1] += l[b][1]

    l[b][1] = 0

n = int(eval(input()))

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

q = int(eval(input()))

total = sum(A)

l = [0 for i in range(10**5+1)]

for _ in range(n):

    l[A[_]] += 1

for i in range(q):

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

    total += (c * l[b])

    total -= (b * l[b])

    print(total)

    l[c] += l[b]

    l[b] = 0

n = int(eval(input()))
A = list(map(int, input().split()))
q = int(eval(input()))
total = sum(A)
l = [[i, 0] for i in range(10**5 + 1)]
for _ in range(n):
    l[A[_]][1] += 1
for i in range(q):
    b, c = list(map(int, input().split()))
    total -= l[b][0] * l[b][1]
    total += l[c][0] * l[b][1]
    print(total)
    l[c][1] += l[b][1]
    l[b][1] = 0

n = int(eval(input()))
A = list(map(int, input().split()))
q = int(eval(input()))
total = sum(A)
l = [0 for i in range(10**5 + 1)]
for _ in range(n):
    l[A[_]] += 1
for i in range(q):
    b, c = list(map(int, input().split()))
    total += c * l[b]
    total -= b * l[b]
    print(total)
    l[c] += l[b]
    l[b] = 0


Input:
n, x = [int(i) for i in input().split()]

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

count = 0

previous = 0

for i in a:

    if i + previous > x:

        excess = i + previous - x

        count += excess

        previous = x - previous

    else: # if not exceeding x.

        previous = i

print(count)

import sys

n, x, *a = list(map(int, sys.stdin.read().split()))

def main():

    cnt = 0

    lim = x

    for c in a:

        if c > lim:

            cnt += c - lim

            lim = x - lim

        else:

            lim = x - c

    return cnt

if __name__ == '__main__':

    ans = main()

    print(ans)

import sys

n, x, *a = list(map(int, sys.stdin.read().split()))

def main():
    cnt = 0
    lim = x
    for c in a:
        if c > lim:
            cnt += c - lim
            lim = x - lim
        else:
            lim = x - c
    return cnt

if __name__ == "__main__":
    ans = main()
    print(ans)

-n, x = [int(i) for i in input().split()]

+n, x, *a = list(map(int, sys.stdin.read().split()))


Input:
import heapq

from collections import deque

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

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

AB.sort(key=lambda x:(x[0], x[1]))

for i in range(N):

  AB[i][1]=-AB[i][1]

d=deque(AB)

ans=0

h=[]

for i in range(M+1):

  if not d and not h:

    break

  while d and d[0][0]<=i:

    heapq.heappush(h, d.popleft()[1])

  if h:

    ans-=heapq.heappop(h)

print(ans)

import heapq

from collections import deque

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

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

AB.sort(key=lambda x:x[0])

d=deque(AB)

h=[]

ans=0

for i in range(M+1):

    while d and d[0][0]<=i:

        heapq.heappush(h, -d.popleft()[1])

    if h:

        ans-=heapq.heappop(h)

print(ans)

import heapq
from collections import deque

N, M = list(map(int, input().split()))
AB = [list(map(int, input().split())) for _ in range(N)]
AB.sort(key=lambda x: (x[0], x[1]))
for i in range(N):
    AB[i][1] = -AB[i][1]
d = deque(AB)
ans = 0
h = []
for i in range(M + 1):
    if not d and not h:
        break
    while d and d[0][0] <= i:
        heapq.heappush(h, d.popleft()[1])
    if h:
        ans -= heapq.heappop(h)
print(ans)

import heapq
from collections import deque

N, M = list(map(int, input().split()))
AB = [list(map(int, input().split())) for _ in range(N)]
AB.sort(key=lambda x: x[0])
d = deque(AB)
h = []
ans = 0
for i in range(M + 1):
    while d and d[0][0] <= i:
        heapq.heappush(h, -d.popleft()[1])
    if h:
        ans -= heapq.heappop(h)
print(ans)

-        heapq.heappush(h, d.popleft()[1])

+        heapq.heappush(h, -d.popleft()[1])


Input:
def dfs(i, A, B, C):

    global ans

    if i == n:

        if A and B and C:

            ans = min(ans, abs(a - sum(A)) + abs(b - sum(B)) + abs(c - sum(C)) + (len(A) + len(B) + len(C) - 3) * 10)

    else:

        dfs(i + 1, A, B, C)

        dfs(i + 1, A + [L[i]], B, C)

        dfs(i + 1, A, B + [L[i]], C)

        dfs(i + 1, A, B, C + [L[i]])

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

L = [int(eval(input())) for i in range(n)]

ans = float("inf")

dfs(0, [], [], [])

print(ans)

def dfs(i, a, b, c, plus):

    global ans

    if i == n:

        if a and b and c:

            mp = abs(a - A) + abs(b - B) + abs(c - C) + (plus - 3) * 10

            ans = min(ans, mp)

    else:

        dfs(i + 1, a, b, c, plus)

        dfs(i + 1, a + l[i], b, c, plus + 1)

        dfs(i + 1, a, b + l[i], c, plus + 1)

        dfs(i + 1, a, b, c + l[i], plus + 1)

n, A, B, C = list(map(int, input().split()))

l = [int(eval(input())) for i in range(n)]

ans = float("inf")

dfs(0, 0, 0, 0, 0)

print(ans)

def dfs(i, A, B, C):
    global ans
    if i == n:
        if A and B and C:
            ans = min(
                ans,
                abs(a - sum(A))
                + abs(b - sum(B))
                + abs(c - sum(C))
                + (len(A) + len(B) + len(C) - 3) * 10,
            )
    else:
        dfs(i + 1, A, B, C)
        dfs(i + 1, A + [L[i]], B, C)
        dfs(i + 1, A, B + [L[i]], C)
        dfs(i + 1, A, B, C + [L[i]])

n, a, b, c = list(map(int, input().split()))
L = [int(eval(input())) for i in range(n)]
ans = float("inf")
dfs(0, [], [], [])
print(ans)

+            mp = abs(a - A) + abs(b - B) + abs(c - C) + (plus - 3) * 10

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

-L = [int(eval(input())) for i in range(n)]

+n, A, B, C = list(map(int, input().split()))

+l = [int(eval(input())) for i in range(n)]


Input:
n=int(eval(input()))

s=[]

for i in range(n):

  s.append("".join(sorted(eval(input()))))

#sss=set(s)

ans=0

import collections

c=collections.Counter(s)

for l in list(c.values()):

  ans+=l*(l-1)*(1/2)

print((int(ans)))

from collections import defaultdict

d=defaultdict(int)

n,*s=open(0).read().split()

for i in s:d["".join(sorted(list(i)))]+=1

print((sum(v*(v-1)//2 for v in list(d.values()))))

n = int(eval(input()))
s = []
for i in range(n):
    s.append("".join(sorted(eval(input()))))
# sss=set(s)
ans = 0
import collections

c = collections.Counter(s)
for l in list(c.values()):
    ans += l * (l - 1) * (1 / 2)
print((int(ans)))

from collections import defaultdict

d = defaultdict(int)
n, *s = open(0).read().split()
for i in s:
    d["".join(sorted(list(i)))] += 1
print((sum(v * (v - 1) // 2 for v in list(d.values()))))

-    s.append("".join(sorted(eval(input()))))

+print((sum(v * (v - 1) // 2 for v in list(d.values()))))


Input:
def read_int():

    return int(input().strip())

def read_ints():

    return list(map(int, input().strip().split(' ')))

def solve():

    # dp[i] = min(abs(h[i]-h[i-1])+dp[i-1], abs(h[i]-h[i-2])+dp[i-2])

    N = read_int()

    h = read_ints()

    dp = [0, abs(h[1]-h[0])]

    for i in range(2, N):

        dp.append(min(abs(h[i]-h[i-1])+dp[i-1], abs(h[i]-h[i-2])+dp[i-2]))

    return dp[-1]

if __name__ == '__main__':

    print((solve()))

def read_int():

    return int(input().strip())

def read_ints():

    return list(map(int, input().strip().split(' ')))

def solve():

    # dp[i] = min(abs(h[i]-h[i-1])+dp[i-1], abs(h[i]-h[i-2])+dp[i-2])

    N = read_int()

    h = read_ints()

    a, b = 0, abs(h[1]-h[0])

    for i in range(2, N):

        b, a = min(abs(h[i]-h[i-1])+b, abs(h[i]-h[i-2])+a), b

    return b

if __name__ == '__main__':

    print((solve()))

def read_int():
    return int(input().strip())

def read_ints():
    return list(map(int, input().strip().split(" ")))

def solve():
    # dp[i] = min(abs(h[i]-h[i-1])+dp[i-1], abs(h[i]-h[i-2])+dp[i-2])
    N = read_int()
    h = read_ints()
    dp = [0, abs(h[1] - h[0])]
    for i in range(2, N):
        dp.append(
            min(abs(h[i] - h[i - 1]) + dp[i - 1], abs(h[i] - h[i - 2]) + dp[i - 2])
        )
    return dp[-1]

if __name__ == "__main__":
    print((solve()))

def read_int():
    return int(input().strip())

def read_ints():
    return list(map(int, input().strip().split(" ")))

def solve():
    # dp[i] = min(abs(h[i]-h[i-1])+dp[i-1], abs(h[i]-h[i-2])+dp[i-2])
    N = read_int()
    h = read_ints()
    a, b = 0, abs(h[1] - h[0])
    for i in range(2, N):
        b, a = min(abs(h[i] - h[i - 1]) + b, abs(h[i] - h[i - 2]) + a), b
    return b

if __name__ == "__main__":
    print((solve()))


Input:
import math

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

print((b // x - (a - 1) // x))


Input:
def is_perfect_power(n):

    if n == 1:

        return True

    div = 2

    divs = []

    while n != 1:

        if n % div == 0:

            n //= div

            divs.append(div)

        else:

            div += 1

    divs_d = {d: 0 for d in set(divs)}

    for d in divs:

        divs_d[d] += 1

    divs_s = {n for n in list(divs_d.values())}

    if min(divs_s) > 1:

        for d in divs_s:

            if d % min(divs_s) != 0:

                return False

    else:

        return False

    return True

X = int(eval(input()))

for x in range(X, 0, -1):

    if is_perfect_power(x):

        print(x)

        break

-    divs_s = {n for n in list(divs_d.values())}