Input:
from heapq import heappop, heappush

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

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

hq = []

for aa in a:

    heappush(hq, (-aa, 1))

for _ in range(m):

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

    heappush(hq, (-c, b))

rest = n

ans = 0

while rest > 0:

    num, cnt = heappop(hq)

    num *= (-1)

    use = min(rest, cnt)

    ans += use * num

    rest -= use

print(ans)

def main():

    from collections import Counter

    from operator import itemgetter

    import sys

    input = sys.stdin.readline

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

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

    ctr = Counter(a)

    for _ in range(M):

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

        ctr[c] += b

    ans = 0

    rest = N

    for integer, count in sorted(list(ctr.items()), key=itemgetter(0), reverse=True):

        take = min(rest, count)

        ans += take * integer

        rest -= take

        if not rest:

            break

    print(ans)

if __name__ == '__main__':

    main()

# import sys

# input = sys.stdin.readline

#

# sys.setrecursionlimit(10 ** 7)

#

# (int(x)-1 for x in input().split())

# rstrip()

from heapq import heappop, heappush

n, m = list(map(int, input().split()))
a = tuple(map(int, input().split()))
hq = []
for aa in a:
    heappush(hq, (-aa, 1))
for _ in range(m):
    b, c = list(map(int, input().split()))
    heappush(hq, (-c, b))
rest = n
ans = 0
while rest > 0:
    num, cnt = heappop(hq)
    num *= -1
    use = min(rest, cnt)
    ans += use * num
    rest -= use
print(ans)

def main():
    from collections import Counter
    from operator import itemgetter
    import sys

    input = sys.stdin.readline
    N, M = list(map(int, input().split()))
    a = list(map(int, input().split()))
    ctr = Counter(a)
    for _ in range(M):
        b, c = list(map(int, input().split()))
        ctr[c] += b
    ans = 0
    rest = N
    for integer, count in sorted(list(ctr.items()), key=itemgetter(0), reverse=True):
        take = min(rest, count)
        ans += take * integer
        rest -= take
        if not rest:
            break
    print(ans)

if __name__ == "__main__":
    main()
# import sys
# input = sys.stdin.readline
#
# sys.setrecursionlimit(10 ** 7)
#
# (int(x)-1 for x in input().split())
# rstrip()

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

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

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

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

+    for integer, count in sorted(list(ctr.items()), key=itemgetter(0), reverse=True):


Input:
A,B,C,X,Y = list(map(int,input().split()))

l = []

for i in range(max(X,Y)+1):

    T = i * C * 2

    if i < X:

        T += (X-i)*A

    if i < Y:

        T += (Y-i)*B

    l.append(T)

l.sort()

print((l[0]))

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

ans = 0

if 2*C <= A+B:

    Z = min(X,Y)

    ans = 2*C*Z

    X -= Z

    Y -= Z

ans += min(2*C*X,A*X)

ans += min(2*C*Y,B*Y)

print(ans)

A, B, C, X, Y = list(map(int, input().split()))
l = []
for i in range(max(X, Y) + 1):
    T = i * C * 2
    if i < X:
        T += (X - i) * A
    if i < Y:
        T += (Y - i) * B
    l.append(T)
l.sort()
print((l[0]))

A, B, C, X, Y = list(map(int, input().split()))
ans = 0
if 2 * C <= A + B:
    Z = min(X, Y)
    ans = 2 * C * Z
    X -= Z
    Y -= Z
ans += min(2 * C * X, A * X)
ans += min(2 * C * Y, B * Y)
print(ans)

-l = []
-for i in range(max(X, Y) + 1):
-    T = i * C * 2
-    if i < X:
-        T += (X - i) * A
-    if i < Y:
-        T += (Y - i) * B
-    l.append(T)
-l.sort()
-print((l[0]))
+ans = 0
+if 2 * C <= A + B:
+    Z = min(X, Y)
+    ans = 2 * C * Z
+    X -= Z
+    Y -= Z
+ans += min(2 * C * X, A * X)
+ans += min(2 * C * Y, B * Y)
+print(ans)


Input:
import collections

import sys

a=input()

b=[]

for i in a:

  b.append(i)

b.sort()

c=collections.Counter(b)

c=list(c.values())

for i in range(len(c)):

  if int(c[i])%2==0:

    q=0

  else:

    q=1

    print('No')

    sys.exit()

print('Yes')

w = list(input())

s = set(w)

for i in s:

  if w.count(i)%2 != 0:

    print("No")

    break

else:

  print("Yes")

import collections
import sys

a = input()
b = []
for i in a:
    b.append(i)
b.sort()
c = collections.Counter(b)
c = list(c.values())
for i in range(len(c)):
    if int(c[i]) % 2 == 0:
        q = 0
    else:
        q = 1
        print("No")
        sys.exit()
print("Yes")

w = list(input())
s = set(w)
for i in s:
    if w.count(i) % 2 != 0:
        print("No")
        break
else:
    print("Yes")

-import collections
-import sys
-a = input()
-b = []
-for i in a:
-    b.append(i)
-b.sort()
-c = collections.Counter(b)
-c = list(c.values())
-for i in range(len(c)):
-    if int(c[i]) % 2 == 0:
-        q = 0
-    else:
-        q = 1
+w = list(input())
+s = set(w)
+for i in s:
+    if w.count(i) % 2 != 0:
-        sys.exit()
-print("Yes")
+        break
+else:
+    print("Yes")


Input:
#ABC951B/Sum_of_Three_Integers

K, S = list(map(int, input().split()))

ans = 0

for x in range(0, K+1):

    for y in range(0, K+1):

        z = S - x - y

        if 0 <= z and z <= K:

            ans += 1

print(ans)

K, S = list(map(int, input().split()))

ans = 0

for X in range(K+1):

    for Y in range(K+1):

        Z = S - X - Y

        if Z >= 0 and Z <= K:

            ans += 1

print(ans)

# ABC951B/Sum_of_Three_Integers
K, S = list(map(int, input().split()))
ans = 0
for x in range(0, K + 1):
    for y in range(0, K + 1):
        z = S - x - y
        if 0 <= z and z <= K:
            ans += 1
print(ans)

K, S = list(map(int, input().split()))
ans = 0
for X in range(K + 1):
    for Y in range(K + 1):
        Z = S - X - Y
        if Z >= 0 and Z <= K:
            ans += 1
print(ans)

-# ABC951B/Sum_of_Three_Integers
-for x in range(0, K + 1):
-    for y in range(0, K + 1):
-        z = S - x - y
-        if 0 <= z and z <= K:
+for X in range(K + 1):
+    for Y in range(K + 1):
+        Z = S - X - Y
+        if Z >= 0 and Z <= K:


Input:
n=int(input())-1

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

i=0

for j in range(n):

 if A[j]<=A[-1]:A[i],A[j]=A[j],A[i];i+=1

A[i],A[n]=A[n],A[i]

print((" ".join(map(str,A[:i]))+" ["+str(A[i])+"] "+" ".join(map(str,A[i+1:]))))

n = int(input()) - 1
A = list(map(int, input().split()))
i = 0
for j in range(n):
    if A[j] <= A[-1]:
        A[i], A[j] = A[j], A[i]
        i += 1
A[i], A[n] = A[n], A[i]
print(
    (
        " ".join(map(str, A[:i]))
        + " ["
        + str(A[i])
        + "] "
        + " ".join(map(str, A[i + 1 :]))
    )
)

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


Input:
N = int(input())

mem = [[0]*10 for _ in range(10)]

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

    a = int(str(i)[0])

    b = int(str(i)[-1])

    mem[a][b] += 1

ans = 0

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

    a = int(str(i)[0])

    b = int(str(i)[-1])

    ans += mem[b][a]

print(ans)

N = int(input())

mem=[[0] * 10 for _ in range(10)]

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

    s = str(i)

    mem[int(s[0])][int(s[-1])] += 1

ans = 0

for i in range(1, 10):

    for j in range(1, 10):

        ans += mem[i][j] * mem[j][i]

print(ans)

N = int(input())
mem = [[0] * 10 for _ in range(10)]
for i in range(1, N + 1):
    a = int(str(i)[0])
    b = int(str(i)[-1])
    mem[a][b] += 1
ans = 0
for i in range(1, N + 1):
    a = int(str(i)[0])
    b = int(str(i)[-1])
    ans += mem[b][a]
print(ans)

N = int(input())
mem = [[0] * 10 for _ in range(10)]
for i in range(1, N + 1):
    s = str(i)
    mem[int(s[0])][int(s[-1])] += 1
ans = 0
for i in range(1, 10):
    for j in range(1, 10):
        ans += mem[i][j] * mem[j][i]
print(ans)


Input:
w = input()

for l in w:

	if w.count(l) % 2 == 1:

		print("No")

		break

else:

	print("Yes")

from collections import Counter

s = input()

c = list(Counter(s).values())

for n in c:

	if n & 1 == 1:

		print("No")

		break

else:

	print("Yes")

-w = input()
-for l in w:
-    if w.count(l) % 2 == 1:
+from collections import Counter
+
+s = input()
+c = list(Counter(s).values())
+for n in c:
+    if n & 1 == 1:


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

tmp=str(a)

c=0

for i in range(a,b+1):

    tmp=str(i)

    tmp2=""

    for s in range(len(tmp)):

        tmp2=tmp2+tmp[len(tmp)-1-s]

    if tmp==tmp2:

        c=c+1

print(c)

def main():

    #1. input

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

    ans = 0

    #2. from A to B

    for i in range(a, b+1):

        #2.1. judge if the number is palindromic

        if (str(i)[0]==str(i)[4]) and (str(i)[1]==str(i)[3]):

            ans = ans+1

    #3. output

    print(ans)

if __name__ == '__main__':

    main()

a, b = list(map(int, input().split()))
tmp = str(a)
c = 0
for i in range(a, b + 1):
    tmp = str(i)
    tmp2 = ""
    for s in range(len(tmp)):
        tmp2 = tmp2 + tmp[len(tmp) - 1 - s]
    if tmp == tmp2:
        c = c + 1
print(c)

def main():
    # 1. input
    a, b = list(map(int, input().split()))
    ans = 0
    # 2. from A to B
    for i in range(a, b + 1):
        # 2.1. judge if the number is palindromic
        if (str(i)[0] == str(i)[4]) and (str(i)[1] == str(i)[3]):
            ans = ans + 1
    # 3. output
    print(ans)

if __name__ == "__main__":
    main()

-        tmp2 = tmp2 + tmp[len(tmp) - 1 - s]

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

+        # 2.1. judge if the number is palindromic


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

ans=0

for i in range(k+1):

    for j in range(k+1):

        z=s-i-j

        if 0<=z<=k:

            ans+=1

print(ans)

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

ans=0

for i in range(k+1):

    for j in range(k+1):

        if 0<=s-i-j<=k:

            ans+=1

print(ans)

k, s = list(map(int, input().split()))
ans = 0
for i in range(k + 1):
    for j in range(k + 1):
        z = s - i - j
        if 0 <= z <= k:
            ans += 1
print(ans)

k, s = list(map(int, input().split()))
ans = 0
for i in range(k + 1):
    for j in range(k + 1):
        if 0 <= s - i - j <= k:
            ans += 1
print(ans)


Input:
import sys, re

from collections import deque, defaultdict, Counter

from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd

from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left, insort, insort_left

from heapq import heappush, heappop

from functools import reduce, lru_cache

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

def INT(): return int(input())

def MAP(): return map(int, input().split())

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

def TUPLE(): return tuple(map(int, input().split()))

def ZIP(n): return zip(*(MAP() for _ in range(n)))

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10 ** 9 + 7

#mod = 998244353

from decimal import *

#import numpy as np

#decimal.getcontext().prec = 10

X, Y, Z, K = MAP()

A = sorted(LIST(), reverse = True)

B = sorted(LIST(), reverse = True)

C = sorted(LIST(), reverse = True)

AB = []

for i in range(X):

	for j in range(Y):

		AB.append(A[i]+B[j])

AB.sort(reverse = True)

AB = AB[:3000]

ABC = sorted([C[0]+AB[i] for i in range(min(3000, X*Y))], reverse = True)

for j in range(1, Z):

	ABC_tmp = sorted([C[j]+AB[i] for i in range(min(3000, X*Y))])

	ABC += ABC_tmp

	ABC.sort(reverse = True)

	ABC = ABC[:3000]

print(*ABC[:K], sep= "\n")

import sys, re

from collections import deque, defaultdict, Counter

from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd

from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left, insort, insort_left

from heapq import heappush, heappop

from functools import reduce, lru_cache

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

def INT(): return int(input())

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

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

def TUPLE(): return tuple(map(int, input().split()))

def ZIP(n): return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10 ** 9 + 7

#mod = 998244353

from decimal import *

#import numpy as np

#decimal.getcontext().prec = 10

X, Y, Z, K = MAP()

A = sorted(LIST(), reverse = True)

B = sorted(LIST(), reverse = True)

C = sorted(LIST(), reverse = True)

ans = []

for i in range(X):

	for j in range(Y):

		for k in range(Z):

			if (i+1)*(j+1)*(k+1) <= K:

				ans.append(A[i]+B[j]+C[k])

			else:

				break

for a in sorted(ans)[::-1][:K]:

	print(a)

import sys, re
from collections import deque, defaultdict, Counter
from math import (
    ceil,
    sqrt,
    hypot,
    factorial,
    pi,
    sin,
    cos,
    tan,
    asin,
    acos,
    atan,
    radians,
    degrees,
    log2,
    gcd,
)
from itertools import (
    accumulate,
    permutations,
    combinations,
    combinations_with_replacement,
    product,
    groupby,
)
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache

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

def INT():
    return int(input())

def MAP():
    return map(int, input().split())

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

def TUPLE():
    return tuple(map(int, input().split()))

def ZIP(n):
    return zip(*(MAP() for _ in range(n)))

sys.setrecursionlimit(10**9)
INF = float("inf")
mod = 10**9 + 7
# mod = 998244353
from decimal import *

# import numpy as np
# decimal.getcontext().prec = 10
X, Y, Z, K = MAP()
A = sorted(LIST(), reverse=True)
B = sorted(LIST(), reverse=True)
C = sorted(LIST(), reverse=True)
AB = []
for i in range(X):
    for j in range(Y):
        AB.append(A[i] + B[j])
AB.sort(reverse=True)
AB = AB[:3000]
ABC = sorted([C[0] + AB[i] for i in range(min(3000, X * Y))], reverse=True)
for j in range(1, Z):
    ABC_tmp = sorted([C[j] + AB[i] for i in range(min(3000, X * Y))])
    ABC += ABC_tmp
    ABC.sort(reverse=True)
    ABC = ABC[:3000]
print(*ABC[:K], sep="\n")

import sys, re
from collections import deque, defaultdict, Counter
from math import (
    ceil,
    sqrt,
    hypot,
    factorial,
    pi,
    sin,
    cos,
    tan,
    asin,
    acos,
    atan,
    radians,
    degrees,
    log2,
    gcd,
)
from itertools import (
    accumulate,
    permutations,
    combinations,
    combinations_with_replacement,
    product,
    groupby,
)
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache

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

def INT():
    return int(input())

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

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

def TUPLE():
    return tuple(map(int, input().split()))

def ZIP(n):
    return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10**9)
INF = float("inf")
mod = 10**9 + 7
# mod = 998244353
from decimal import *

# import numpy as np
# decimal.getcontext().prec = 10
X, Y, Z, K = MAP()
A = sorted(LIST(), reverse=True)
B = sorted(LIST(), reverse=True)
C = sorted(LIST(), reverse=True)
ans = []
for i in range(X):
    for j in range(Y):
        for k in range(Z):
            if (i + 1) * (j + 1) * (k + 1) <= K:
                ans.append(A[i] + B[j] + C[k])
            else:
                break
for a in sorted(ans)[::-1][:K]:
    print(a)

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

-    return zip(*(MAP() for _ in range(n)))

+    return list(zip(*(MAP() for _ in range(n))))

-ABC = sorted([C[0] + AB[i] for i in range(min(3000, X * Y))], reverse=True)

-    ABC_tmp = sorted([C[j] + AB[i] for i in range(min(3000, X * Y))])

+                ans.append(A[i] + B[j] + C[k])


Input:
while True:

    try:

        for i in range(3):

            line = input().strip()

            if line == '0':

                raise Exception

            a = b = 0

            for i, s in enumerate(line):

                if i != 0:

                    if s == 'A':

                        a += 1

                    else:

                        b += 1

            if a > b:

                a += 1

            else:

                b += 1

            print(a, b)

    except:

        break

while True:

    try:

        for i in range(3):

            line = input().strip()

            if line == '0':

                raise Exception

            if line[0] == 'A':

                a = -1

                b = 0

            else:

                a = 0

                b = -1

            for i, s in enumerate(line):

                if s == 'A':

                    a += 1

                else:

                    b += 1

            if a > b:

                a += 1

            else:

                b += 1

            print(a, b)

    except:

        break

while True:
    try:
        for i in range(3):
            line = input().strip()
            if line == "0":
                raise Exception
            a = b = 0
            for i, s in enumerate(line):
                if i != 0:
                    if s == "A":
                        a += 1
                    else:
                        b += 1
            if a > b:
                a += 1
            else:
                b += 1
            print(a, b)
    except:
        break

while True:
    try:
        for i in range(3):
            line = input().strip()
            if line == "0":
                raise Exception
            if line[0] == "A":
                a = -1
                b = 0
            else:
                a = 0
                b = -1
            for i, s in enumerate(line):
                if s == "A":
                    a += 1
                else:
                    b += 1
            if a > b:
                a += 1
            else:
                b += 1
            print(a, b)
    except:
        break


Input:
from bisect import *

n = int(input())

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

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

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

a = sorted(a)

c = sorted(c)

rec = 0

for i in range(n):

    temp = b[i]

    l = bisect_left(a, temp)

    r = bisect_right(c, temp)

    rec += l * (n - r)

print(rec)

from bisect import *

n = int(input())

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

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

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

a.sort()

c.sort()

res = 0

for i in b:

    temp_a = bisect_left(a, i)

    temp_c = n - bisect_right(c, i)

    res += temp_a*temp_c

print(res)

from bisect import *

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
a = sorted(a)
c = sorted(c)
rec = 0
for i in range(n):
    temp = b[i]
    l = bisect_left(a, temp)
    r = bisect_right(c, temp)
    rec += l * (n - r)
print(rec)

from bisect import *

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
a.sort()
c.sort()
res = 0
for i in b:
    temp_a = bisect_left(a, i)
    temp_c = n - bisect_right(c, i)
    res += temp_a * temp_c
print(res)

-a = sorted(a)
-c = sorted(c)
-rec = 0
-for i in range(n):
-    temp = b[i]
-    l = bisect_left(a, temp)
-    r = bisect_right(c, temp)
-    rec += l * (n - r)
-print(rec)
+a.sort()
+c.sort()
+res = 0
+for i in b:
+    temp_a = bisect_left(a, i)
+    temp_c = n - bisect_right(c, i)
+    res += temp_a * temp_c
+print(res)


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

for i in range(N+1):

    for j in range(M+1):

        t = i*M + j*N - i*j*2

        if t==K:

            print('Yes')

            exit()

print('No')

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

for i in range(N+1):

    for j in range(M+1):

        if i*(M-j) + j*(N-i) == K:

            print('Yes')

            exit()

print('No')

N, M, K = list(map(int, input().split()))
for i in range(N + 1):
    for j in range(M + 1):
        t = i * M + j * N - i * j * 2
        if t == K:
            print("Yes")
            exit()
print("No")

N, M, K = list(map(int, input().split()))
for i in range(N + 1):
    for j in range(M + 1):
        if i * (M - j) + j * (N - i) == K:
            print("Yes")
            exit()
print("No")


Input:
a,b,c,d,e,f=[int(input()) for _ in range(6)]

print((sum([a,b,c,d,max(e,f)])-min([a,b,c,d])))

print((sum(sorted(int(input()) for _ in range(4))[1:])+max([int(input()) for _ in range(2)])))

a, b, c, d, e, f = [int(input()) for _ in range(6)]
print((sum([a, b, c, d, max(e, f)]) - min([a, b, c, d])))

print(
    (
        sum(sorted(int(input()) for _ in range(4))[1:])
        + max([int(input()) for _ in range(2)])
    )
)

-a, b, c, d, e, f = [int(input()) for _ in range(6)]

-print((sum([a, b, c, d, max(e, f)]) - min([a, b, c, d])))

+        sum(sorted(int(input()) for _ in range(4))[1:])

+        + max([int(input()) for _ in range(2)])


Input:
# AtCoder Beginner Contest 095 C - Half and Half

import sys

A, B, C, X, Y = list(map(int, sys.stdin.readline().strip().split()))

ans = A * X + B * Y

for z in range(2, 2 * 10 ** 5 + 1, 2):

    x = max(X - int(z / 2), 0)

    y = max(Y - int(z / 2), 0)

    price = A * x + B * y + C * z

    ans = min(price, ans)

print(ans)

# AtCoder Beginner Contest 095 C - Half and Half

import sys

A, B, C, X, Y = list(map(int, sys.stdin.readline().strip().split()))

"""

ans = A * X + B * Y

for z in range(2, 2 * 10 ** 5 + 1, 2):

    x = max(X - int(z / 2), 0)

    y = max(Y - int(z / 2), 0)

    price = A * x + B * y + C * z

    ans = min(price, ans)

print(ans)

"""

price1 = A * X + B * Y

price2 = C * 2 * X + B * max(Y - X, 0)

price3 = A * max(X - Y, 0) + C * 2 * Y

print((min(price1, price2, price3)))

# AtCoder Beginner Contest 095 C - Half and Half
import sys

A, B, C, X, Y = list(map(int, sys.stdin.readline().strip().split()))
ans = A * X + B * Y
for z in range(2, 2 * 10**5 + 1, 2):
    x = max(X - int(z / 2), 0)
    y = max(Y - int(z / 2), 0)
    price = A * x + B * y + C * z
    ans = min(price, ans)
print(ans)


Input:
from collections import defaultdict

N = int(input())

d = defaultdict(int)

for i in range(N):

    S = input()

    d[S] += 1

m = 0

for k in list(d.keys()):

    m = max(d[k],m)

li = []

for k in list(d.keys()):

    if d[k] == m:

        li.append(k)

li.sort()

for l in li:

    print(l)

from collections import defaultdict

N = int(input())

Ss = [input() for i in range(N)]

d = defaultdict(int)

for S in Ss:

    d[S] += 1

mx = max([d[k] for k in list(d.keys())])

ans = []

for k in list(d.keys()):

    if d[k] == mx:

       ans.append(k)

for a in sorted(ans):

    print(a)

from collections import defaultdict

N = int(input())
d = defaultdict(int)
for i in range(N):
    S = input()
    d[S] += 1
m = 0
for k in list(d.keys()):
    m = max(d[k], m)
li = []
for k in list(d.keys()):
    if d[k] == m:
        li.append(k)
li.sort()
for l in li:
    print(l)

+mx = max([d[k] for k in list(d.keys())])


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

L,R = [],[]

for i in range(M):

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

    L.append(l)

    R.append(r)

ans = min(R)-max(L)+1

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

# coding: utf-8

import sys

sr = lambda: sys.stdin.readline().rstrip()

ir = lambda: int(sr())

lr = lambda: list(map(int, sr().split()))

N, M = lr()

L = 0; R = 10 ** 6

for _ in range(M):

    l, r = lr()

    if l > L:

        L = l

    if r < R:

        R = r

answer = max(0, R - L + 1)

print(answer)

N, M = list(map(int, input().split()))
L, R = [], []
for i in range(M):
    l, r = list(map(int, input().split()))
    L.append(l)
    R.append(r)
ans = min(R) - max(L) + 1
print((ans if ans >= 0 else 0))

# coding: utf-8
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
N, M = lr()
L = 0
R = 10**6
for _ in range(M):
    l, r = lr()
    if l > L:
        L = l
    if r < R:
        R = r
answer = max(0, R - L + 1)
print(answer)

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

+sr = lambda: sys.stdin.readline().rstrip()

+lr = lambda: list(map(int, sr().split()))


Input:
n = int(input())

l = []

for i in range(1,1000001):

    a = n / i

    if a.is_integer():

        l.append(i+n/i)

print((int(min(l)-2)))

n = int(input())
l = []
for i in range(1, 1000001):
    a = n / i
    if a.is_integer():
        l.append(i + n / i)
print((int(min(l) - 2)))


Input:
n = int(input())

import math

m = int(math.sqrt(n))+1

anss = []

for x in range(1, m+1):

  y = n//x

  z = n%x

  if z == 0:

    anss.append(abs(x-1)+abs(y-1))

print((min(anss)))

n = int(input())

def make_divisors(n):

    divisors = []

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

        if n % i == 0:

            divisors.append(i)

            if i != n // i:

                divisors.append(n//i)

    #divisors.sort(reverse=True)

    return divisors

l = make_divisors(n)

min_ = float('inf')

for i in range(len(l)):

    min_ = min(min_, l[i]-1+n//l[i]-1)

print(min_)

n = int(input())
import math

m = int(math.sqrt(n)) + 1
anss = []
for x in range(1, m + 1):
    y = n // x
    z = n % x
    if z == 0:
        anss.append(abs(x - 1) + abs(y - 1))
print((min(anss)))

n = int(input())

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5) + 1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n // i)
    # divisors.sort(reverse=True)
    return divisors

l = make_divisors(n)
min_ = float("inf")
for i in range(len(l)):
    min_ = min(min_, l[i] - 1 + n // l[i] - 1)
print(min_)

-        anss.append(abs(x - 1) + abs(y - 1))

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

+                divisors.append(n // i)


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

if a*b%2 == 1:

    print("Odd")

else:

    print("Even")

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

print(('Odd'if a&b&1 else 'Even'))

a, b = list(map(int, input().split()))
if a * b % 2 == 1:
    print("Odd")
else:
    print("Even")

a, b = list(map(int, input().split()))
print(("Odd" if a & b & 1 else "Even"))

+print(("Odd" if a & b & 1 else "Even"))


Input:
n = int(input())

m = 10**9 + 7

# ans = [0] * (n + 1)

ans = [0] * 2200

ans[0] = 1

# ans[3] = 1

# ans[4] = 1

# ans[5] = 1

for i in range(3, n + 1):

    for j in range(i - 2):

        ans[i] += ans[j]

        ans[i] %= m

print((ans[n]))

# print(ans[:10])

-    for j in range(i - 2):
-        ans[i] += ans[j]
-        ans[i] %= m
+    ans[i] = ans[i - 1] + ans[i - 3]
+    ans[i] %= m
+    # for j in range(i - 2):
+    #     ans[i] += ans[j]
+    #     ans[i] %= m


Input:
import sys

input = sys.stdin.readline

read = sys.stdin.read

n = int(input())

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

L = sorted([(j, i) for i, j in enumerate(A)])

count = 0

for i in range(n):

  if (L[i][1]-i)%2:

    count += 1

ans = (count+1) // 2

print(ans)

import sys

input = sys.stdin.readline

read = sys.stdin.read

n = int(input())

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

L = sorted([(j, i) for i, j in enumerate(A)])

count = 0

for i in range(n):

  count += (L[i][1]-i)%2

ans = (count+1) // 2

print(ans)

import sys

input = sys.stdin.readline
read = sys.stdin.read
n = int(input())
A = list(map(int, read().split()))
L = sorted([(j, i) for i, j in enumerate(A)])
count = 0
for i in range(n):
    if (L[i][1] - i) % 2:
        count += 1
ans = (count + 1) // 2
print(ans)

import sys

input = sys.stdin.readline
read = sys.stdin.read
n = int(input())
A = list(map(int, read().split()))
L = sorted([(j, i) for i, j in enumerate(A)])
count = 0
for i in range(n):
    count += (L[i][1] - i) % 2
ans = (count + 1) // 2
print(ans)


Input:
# Acceptance of input

import sys

file_input = sys.stdin

X, Y, E = list(map(int, file_input.readline().split()))

v_num = X + Y + 2

adj_mat = [[0] * (v_num) for i in range(v_num)]

for line in file_input:

    x, y = list(map(int, line.split()))

    adj_mat[x][X + y] = 1

s = X + Y

t = s + 1

for i in range(X):

    adj_mat[s][i] = 1

for i in range(X, s):

    adj_mat[i][t] = 1

# Dinic's algorithm

import collections

# BFS for residual capacity network to construct level graph

def bfs(start, goal, parent):

    unvisited = [True] * v_num

    queue = collections.deque()

    queue.append(start)

    unvisited[start] = False

    while queue:

        u = queue.popleft()

        for v, r_capacity in enumerate(adj_mat[u]):

            if unvisited[v] and (r_capacity > 0):

                parent[v].append(u)

                queue.append(v)

                unvisited[v] = False

    return unvisited[goal]

# DFS for level graph and construct blocking flow

def dfs(goal, path, parent, blocking_flow):

    v = path[-1]

    if v == goal:

        aug_path_flow = 10000

        for x, y in zip(path[1:], path[:-1]):

            aug_path_flow = min(aug_path_flow, adj_mat[x][y])

        for x, y in zip(path[1:], path[:-1]):

            adj_mat[x][y] -= aug_path_flow

            adj_mat[y][x] += aug_path_flow

        blocking_flow[0] += aug_path_flow

    else:

        for u in parent[v]:

            path.append(u)

            dfs(goal, path, parent, blocking_flow)

            path.pop()

def dinic(source, sink):

    max_flow = 0

    parent = [[] for i in range(v_num)]

    while not bfs(source, sink, parent):

        blocking_flow = [0]

        path = [sink]

        # search in reverse direction from sink

        dfs(source, path, parent, blocking_flow)

        max_flow += blocking_flow[0]

        parent = [[] for i in range(v_num)]

    return max_flow

# output

print((dinic(s, t)))

# Acceptance of input

import sys

file_input = sys.stdin

X, Y, E = list(map(int, file_input.readline().split()))

v_num = X + Y + 2

adj_mat = [[0] * (v_num) for i in range(v_num)]

for line in file_input:

    x, y = list(map(int, line.split()))

    adj_mat[x][X + y] = 1

s = X + Y

t = s + 1

for i in range(X):

    adj_mat[s][i] = 1

for i in range(X, s):

    adj_mat[i][t] = 1

# Dinic's algorithm

import collections

# BFS for residual capacity network to construct level graph

def bfs(start, goal, parent):

    level = [v_num] * v_num

    unvisited = [True] * v_num

    queue = collections.deque()

    queue.append(start)

    level[start] = 0

    unvisited[start] = False

    while queue:

        u = queue.popleft()

        next_level = level[u] + 1

        for v, r_capacity in enumerate(adj_mat[u]):

            if (level[v] >= next_level) and (r_capacity > 0):

                level[v] = next_level

                parent[v].append(u)

                if unvisited[v]:

                    queue.append(v)

                    unvisited[v] = False

    return level[goal]

# DFS for level graph and construct blocking flow

def dfs(goal, path, parent, blocking_flow):

    v = path[-1]

    if v == goal:

        aug_path_flow = 10000

        for x, y in zip(path[1:], path[:-1]):

            aug_path_flow = min(aug_path_flow, adj_mat[x][y])

        for x, y in zip(path[1:], path[:-1]):

            adj_mat[x][y] -= aug_path_flow

            adj_mat[y][x] += aug_path_flow

        blocking_flow[0] += aug_path_flow

    else:

        for u in parent[v]:

            path.append(u)

            dfs(goal, path, parent, blocking_flow)

            path.pop()

def dinic(source, sink):

    max_flow = 0

    parent = [[] for i in range(v_num)]

    while bfs(source, sink, parent) != v_num:

        blocking_flow = [0]

        path = [sink]

        # search in reverse direction from sink

        dfs(source, path, parent, blocking_flow)

        max_flow += blocking_flow[0]

        parent = [[] for i in range(v_num)]

    return max_flow

# output

print((dinic(s, t)))

-            if unvisited[v] and (r_capacity > 0):

+            if (level[v] >= next_level) and (r_capacity > 0):

+                    unvisited[v] = False

-    while not bfs(source, sink, parent):

+    while bfs(source, sink, parent) != v_num:


Input:
import sys, re

from collections import deque, defaultdict, Counter

from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2, log

from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left, insort, insort_left

from math import gcd

from heapq import heappush, heappop

from functools import reduce

from decimal import Decimal

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

def INT(): return int(input())

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

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

def ZIP(n): return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10**9 + 7

from decimal import *

N = INT()

xy = []

for i in range(N):

	A = INT()

	xy.append([LIST() for _ in range(A)])

ans = 0

for i in range(1<<N):

	i = list("{:b}".format(i).zfill(N))

	for j in range(N):

		if i[j] == "1":

			for x, y in xy[j]:

				if y != int(i[x-1]):

					break

			else:

				continue

			break

	else:

		tmp = sum([int(x) for x in i])

		ans = max(ans, tmp)

print(ans)

import sys, re

from collections import deque, defaultdict, Counter

from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2, log

from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby

from operator import itemgetter, mul

from copy import deepcopy

from string import ascii_lowercase, ascii_uppercase, digits

from bisect import bisect, bisect_left, insort, insort_left

from math import gcd

from heapq import heappush, heappop

from functools import reduce

from decimal import Decimal

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

def INT(): return int(input())

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

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

def ZIP(n): return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10**9 + 7

from decimal import *

N = INT()

xy = []

for i in range(N):

	A = INT()

	xy.append([LIST() for _ in range(A)])

ans = 0

for X in product((0, 1), repeat=N):

	for j in range(N):

		if X[j] == 1:

			for x, y in xy[j]:

				if X[x-1] != y:

					break

			else:

				continue

			break

	else:

		ans = max(ans, sum(X))

print(ans)

import sys, re
from collections import deque, defaultdict, Counter
from math import (
    ceil,
    sqrt,
    hypot,
    factorial,
    pi,
    sin,
    cos,
    tan,
    asin,
    acos,
    atan,
    radians,
    degrees,
)  # , log2, log
from itertools import (
    accumulate,
    permutations,
    combinations,
    combinations_with_replacement,
    product,
    groupby,
)
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from math import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal

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

def INT():
    return int(input())

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

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

def ZIP(n):
    return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10**9)
INF = float("inf")
mod = 10**9 + 7
from decimal import *

N = INT()
xy = []
for i in range(N):
    A = INT()
    xy.append([LIST() for _ in range(A)])
ans = 0
for i in range(1 << N):
    i = list("{:b}".format(i).zfill(N))
    for j in range(N):
        if i[j] == "1":
            for x, y in xy[j]:
                if y != int(i[x - 1]):
                    break
            else:
                continue
            break
    else:
        tmp = sum([int(x) for x in i])
        ans = max(ans, tmp)
print(ans)

import sys, re
from collections import deque, defaultdict, Counter
from math import (
    ceil,
    sqrt,
    hypot,
    factorial,
    pi,
    sin,
    cos,
    tan,
    asin,
    acos,
    atan,
    radians,
    degrees,
)  # , log2, log
from itertools import (
    accumulate,
    permutations,
    combinations,
    combinations_with_replacement,
    product,
    groupby,
)
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from math import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal

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

def INT():
    return int(input())

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

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

def ZIP(n):
    return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10**9)
INF = float("inf")
mod = 10**9 + 7
from decimal import *

N = INT()
xy = []
for i in range(N):
    A = INT()
    xy.append([LIST() for _ in range(A)])
ans = 0
for X in product((0, 1), repeat=N):
    for j in range(N):
        if X[j] == 1:
            for x, y in xy[j]:
                if X[x - 1] != y:
                    break
            else:
                continue
            break
    else:
        ans = max(ans, sum(X))
print(ans)

-    i = list("{:b}".format(i).zfill(N))


Input:
w = input()

y = list(set(w))

for i in range(len(y)):

    if w.count(y[i]) % 2 != 0:

        print('No')

        exit(0)

print('Yes')

w = list(input())

x = list(set(w))

for i in x:

    y = w.count(i)

    if y % 2 != 0:

        print('No')

        exit(0)

print('Yes')

w = input()
y = list(set(w))
for i in range(len(y)):
    if w.count(y[i]) % 2 != 0:
        print("No")
        exit(0)
print("Yes")

w = list(input())
x = list(set(w))
for i in x:
    y = w.count(i)
    if y % 2 != 0:
        print("No")
        exit(0)
print("Yes")

-w = input()
-y = list(set(w))
-for i in range(len(y)):
-    if w.count(y[i]) % 2 != 0:
+w = list(input())
+x = list(set(w))
+for i in x:
+    y = w.count(i)
+    if y % 2 != 0:


Input:
from collections import defaultdict

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

S = [0] * (N + 1)

for i in range(N):

    S[i + 1] = S[i] + A[i]

d = defaultdict(int)

ans = 0

for j in range(N + 1):

    v = (S[j] - j) % K

    ans += d[v]

    d[v] += 1

    if j >= K - 1:

        d[(S[j - K + 1] - (j - K + 1)) % K] -= 1

print(ans)

from collections import defaultdict

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

x = [0] * (N + 1)

for i in range(N):

    x[i + 1] = x[i] + A[i]

y = [(x[i] - i) % K for i in range(N + 1)]

ctr = defaultdict(int)

ans = 0

for j in range(N + 1):

    ans += ctr[y[j]]

    ctr[y[j]] += 1

    if j - K + 1 >= 0:

        ctr[y[j - K + 1]] -= 1

print(ans)

+y = [(x[i] - i) % K for i in range(N + 1)]


Input:
n=int(input())

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

x.sort()

for p in range(x[0],x[len(x)-1]+1):

    psum=0

    for i in range(len(x)):

        psum=psum+(x[0]-x[i])**2

#    print(psum)

    pmin=psum

    for j in range(x[0]+1,x[len(x)-1]):

        psum=0

        for i in range(len(x)):

            psum=psum+(j-x[i])**2

#        print(psum)

        if pmin>psum:

            pmin=psum

print(pmin)

n=int(input())

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

x.sort()

psum=0

for i in range(len(x)):

    psum=psum+(x[0]-x[i])**2

#    print(psum)

pmin=psum

for j in range(x[0]+1,x[len(x)-1]):

    psum=0

    for i in range(len(x)):

        psum=psum+(j-x[i])**2

#        print(psum)

    if pmin>psum:

        pmin=psum

print(pmin)

n = int(input())
x = list(map(int, input().split()))
x.sort()
for p in range(x[0], x[len(x) - 1] + 1):
    psum = 0
    for i in range(len(x)):
        psum = psum + (x[0] - x[i]) ** 2
    #    print(psum)
    pmin = psum
    for j in range(x[0] + 1, x[len(x) - 1]):
        psum = 0
        for i in range(len(x)):
            psum = psum + (j - x[i]) ** 2
        #        print(psum)
        if pmin > psum:
            pmin = psum
print(pmin)

n = int(input())
x = list(map(int, input().split()))
x.sort()
psum = 0
for i in range(len(x)):
    psum = psum + (x[0] - x[i]) ** 2
#    print(psum)
pmin = psum
for j in range(x[0] + 1, x[len(x) - 1]):
    psum = 0
    for i in range(len(x)):
        psum = psum + (j - x[i]) ** 2
    #        print(psum)
    if pmin > psum:
        pmin = psum
print(pmin)

-for p in range(x[0], x[len(x) - 1] + 1):

+for j in range(x[0] + 1, x[len(x) - 1]):

-    for j in range(x[0] + 1, x[len(x) - 1]):

-            psum = psum + (j - x[i]) ** 2


Input:
import re

S = input()

max = 0

for i in range(len(S)) :

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

        pattern = re.compile(r'[A|T|C|G]{%d}' % int(j - i))

        subStr = S[i:j]

        if pattern.match(subStr) and j - i > max :

            max = j - i

print(max)

S = input()

ans = 0

for i in range(len(S)) :

    for j in range(i, len(S)) :

        if all('ACGT'.count(c) == 1 for c in S[i : j + 1]) :

            ans = max(ans, j - i + 1)

print(ans)

import re

S = input()
max = 0
for i in range(len(S)):
    for j in range(i + 1, len(S) + 1):
        pattern = re.compile(r"[A|T|C|G]{%d}" % int(j - i))
        subStr = S[i:j]
        if pattern.match(subStr) and j - i > max:
            max = j - i
print(max)

S = input()
ans = 0
for i in range(len(S)):
    for j in range(i, len(S)):
        if all("ACGT".count(c) == 1 for c in S[i : j + 1]):
            ans = max(ans, j - i + 1)
print(ans)

-        pattern = re.compile(r"[A|T|C|G]{%d}" % int(j - i))

-        if pattern.match(subStr) and j - i > max:

+        if all("ACGT".count(c) == 1 for c in S[i : j + 1]):


Input:
import itertools

N = int(input())

Nketa = len(str(N))

range_count = [[0 for j in range(10)]for i in range(10)]

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

    mae = int(str(p)[0])

    ato = int(str(p)[-1])

    range_count[mae][ato] += 1

count = 0

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

    a_mae = int(str(j)[0])

    a_ato = int(str(j)[-1])

    b_mae = a_ato

    b_ato = a_mae

    if b_mae == 0:

        continue

    else:

        count += range_count[b_mae][b_ato]

print(count)

n = int(input())

all_count = 0

options = [str(i) for i in range(10)]

maeato = [[0 for i in range(10)] for j in range(10)]

for i in range(n+1):

    checking = str(i)

    maeato[int(checking[0])][int(checking[-1])]+=1

all_count = 0

for i in range(1,10):

    for j in range(1,10):

        for k in range(1,10):

            for p in range(1,10):

                if i == p and j == k:

                    all_count+=maeato[i][j]*maeato[k][p]

print(all_count)

import itertools

N = int(input())
Nketa = len(str(N))
range_count = [[0 for j in range(10)] for i in range(10)]
for p in range(1, N + 1):
    mae = int(str(p)[0])
    ato = int(str(p)[-1])
    range_count[mae][ato] += 1
count = 0
for j in range(1, N + 1):
    a_mae = int(str(j)[0])
    a_ato = int(str(j)[-1])
    b_mae = a_ato
    b_ato = a_mae
    if b_mae == 0:
        continue
    else:
        count += range_count[b_mae][b_ato]
print(count)

n = int(input())
all_count = 0
options = [str(i) for i in range(10)]
maeato = [[0 for i in range(10)] for j in range(10)]
for i in range(n + 1):
    checking = str(i)
    maeato[int(checking[0])][int(checking[-1])] += 1
all_count = 0
for i in range(1, 10):
    for j in range(1, 10):
        for k in range(1, 10):
            for p in range(1, 10):
                if i == p and j == k:
                    all_count += maeato[i][j] * maeato[k][p]
print(all_count)

-range_count = [[0 for j in range(10)] for i in range(10)]

-        count += range_count[b_mae][b_ato]

+maeato = [[0 for i in range(10)] for j in range(10)]

+    maeato[int(checking[0])][int(checking[-1])] += 1

+                    all_count += maeato[i][j] * maeato[k][p]


Input:
s=input()

t=input()

ans=0

if s[0]==t[0]:

    ans+=1

if s[1]==t[1]:

    ans+=1

if s[2]==t[2]:

    ans+=1

print(ans)

s=input()

t=input()

ans=0

for i in range(0,3):

    if s[i]==t[i]:

        ans+=1

print(ans)

s = input()
t = input()
ans = 0
for i in range(0, 3):
    if s[i] == t[i]:
        ans += 1
print(ans)


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

cnt=0

for i in range(k+1):

    for j in range(k+1):

        if 0 <= s-i-j <= k:

            cnt+=1

print(cnt)

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

a=0

for i in range(0,k+1):

    for j in range(0,k+1):

        if 0<=s-i-j<=k:

            a+=1

print(a)

k, s = list(map(int, input().split()))
cnt = 0
for i in range(k + 1):
    for j in range(k + 1):
        if 0 <= s - i - j <= k:
            cnt += 1
print(cnt)

k, s = list(map(int, input().split()))
a = 0
for i in range(0, k + 1):
    for j in range(0, k + 1):
        if 0 <= s - i - j <= k:
            a += 1
print(a)

-cnt = 0
-for i in range(k + 1):
-    for j in range(k + 1):
+a = 0
+for i in range(0, k + 1):
+    for j in range(0, k + 1):
-            cnt += 1
-print(cnt)
+            a += 1
+print(a)


Input:
from math import gcd

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

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

cnt = [0 for _ in range(N)]

for i in range(N):

  a = A[i]

  while a%2 == 0:

    a = a // 2

    cnt[i] += 1

if max(cnt) > min(cnt):

  print((0))

  exit(0)

C = max(cnt)

A = list([x // pow(2,C) for x in A])

def gcd(a,b):

  if a<b:

    a,b = b,a

  while a%b > 0:

    a,b = b,a%b

  return b

def lcm(a,b):

  return a*b//gcd(a,b)

x = A[0]

for a in A[1:]:

  x = lcm(x,a)

x = x * pow(2,C-1)

print(((M // x + 1) // 2))

from math import gcd

N, M = list(map(int, input().split()))
A = list([int(x) for x in input().split()])
cnt = [0 for _ in range(N)]
for i in range(N):
    a = A[i]
    while a % 2 == 0:
        a = a // 2
        cnt[i] += 1
if max(cnt) > min(cnt):
    print((0))
    exit(0)
C = max(cnt)
A = list([x // pow(2, C) for x in A])

def gcd(a, b):
    if a < b:
        a, b = b, a
    while a % b > 0:
        a, b = b, a % b
    return b

def lcm(a, b):
    return a * b // gcd(a, b)

x = A[0]
for a in A[1:]:
    x = lcm(x, a)
x = x * pow(2, C - 1)
print(((M // x + 1) // 2))


Input:
from heapq import *

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

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

heapify(PAIRS)

for _ in range(m):

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

    heappush(PAIRS, [-c, -b])

answer = 0

for _ in range(n):

    pair = heappop(PAIRS)

    answer += -pair[0]

    pair[1] += 1

    if pair[1] != 0:

        heappush(PAIRS, pair)

print(answer)

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

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

for _ in range(m):

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

    PAIRS.append((c, b))

PAIRS.sort(reverse = True)

answer, count = 0, 0

for pair in PAIRS:

    answer += pair[0] * pair[1]

    count += pair[1]

    if count > n:

        answer -= pair[0] * (count - n)

        break

print(answer)

n, m = list(map(int, input().split()))
PAIRS = [(a, 1) for a in map(int, input().split())]
for _ in range(m):
    b, c = list(map(int, input().split()))
    PAIRS.append((c, b))
PAIRS.sort(reverse=True)
answer, count = 0, 0
for pair in PAIRS:
    answer += pair[0] * pair[1]
    count += pair[1]
    if count > n:
        answer -= pair[0] * (count - n)
        break
print(answer)

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

+PAIRS = [(a, 1) for a in map(int, input().split())]

+        answer -= pair[0] * (count - n)


Input:
import math

n = int(input())

ans = math.factorial(n) % (pow(10, 9) + 7)

print(ans)

n = int(input())

ans = 1

mod = 10 ** 9 + 7

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

    ans = (ans * i % mod) % mod

print(ans)

n = int(input())
ans = 1
mod = 10**9 + 7
for i in range(1, n + 1):
    ans = (ans * i % mod) % mod
print(ans)

-ans = math.factorial(n) % (pow(10, 9) + 7)


Input:
k = int(input())

x = 1

if k%7 != 0:

    mod = 9*k

else:

    mod = 9*k//7

for i in range(10**6):

    x = x*10%mod

    if x == 1:

        print((i + 1))

        exit()

print((-1))

k = int(input())

a = 0

for i in range(k + 10):

    a = (a*10 + 7)%k

    if a == 0:

        print((i + 1))

        exit()

print((-1))

k = int(input())
x = 1
if k % 7 != 0:
    mod = 9 * k
else:
    mod = 9 * k // 7
for i in range(10**6):
    x = x * 10 % mod
    if x == 1:
        print((i + 1))
        exit()
print((-1))

k = int(input())
a = 0
for i in range(k + 10):
    a = (a * 10 + 7) % k
    if a == 0:
        print((i + 1))
        exit()
print((-1))


Input:
s = input()

cnt = 0

ans = 0

for c in s:

    if c == 'B':

        cnt += 1

    elif c == 'W':

        ans += cnt

print(ans)

s = input()

ans = 0

b = 0

for ss in s:

    if ss == 'W':

        ans += b

    else:

        b += 1

print(ans)

s = input()
cnt = 0
ans = 0
for c in s:
    if c == "B":
        cnt += 1
    elif c == "W":
        ans += cnt
print(ans)

s = input()
ans = 0
b = 0
for ss in s:
    if ss == "W":
        ans += b
    else:
        b += 1
print(ans)

-cnt = 0
-for c in s:
-    if c == "B":
-        cnt += 1
-    elif c == "W":
-        ans += cnt
+b = 0
+for ss in s:
+    if ss == "W":
+        ans += b
+    else:
+        b += 1


Input:
import math

def pri(n):

    if n < 2:

        return False

    elif n == 2:

        return True

    elif n % 2 == 0:

        return False

    i = 3

    while i <= math.sqrt(n):

        if n % i == 0:

            return False

        i += 2

    return True

l=[i for i in range(110000)if pri(i) ]

while True:

    n = int(input())

    if n == 0: break

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

import math

def pri(n):

    l =[True] * n

    l[0] = l[1] = False

    for i in range(2,n):

        if l[i]:

            for j in range(i*2, n, i):

                l[j] = False

    return l

n=105000

s=pri(n)

l=[i for i in range(n) if s[i]]

while True:

    n = int(input())

    if n == 0: break

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

import math

def pri(n):
    if n < 2:
        return False
    elif n == 2:
        return True
    elif n % 2 == 0:
        return False
    i = 3
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 2
    return True

l = [i for i in range(110000) if pri(i)]
while True:
    n = int(input())
    if n == 0:
        break
    print((sum(l[:n])))

import math

def pri(n):
    l = [True] * n
    l[0] = l[1] = False
    for i in range(2, n):
        if l[i]:
            for j in range(i * 2, n, i):
                l[j] = False
    return l

n = 105000
s = pri(n)
l = [i for i in range(n) if s[i]]
while True:
    n = int(input())
    if n == 0:
        break
    print((sum(l[:n])))

+            for j in range(i * 2, n, i):

-l = [i for i in range(110000) if pri(i)]


Input:
n = int(input())

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

print((sum(l[i]<l[i+1]<l[i+2] or l[i]>l[i+1]>l[i+2] for i in range(n-2))))

n=int(input())

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

a=0

for i in range(n-2):

  p,q,r=l[i:i+3]

  if p<q<r or r<q<p: a+=1

print(a)

n = int(input())
l = list(map(int, input().split()))
print(
    (
        sum(
            l[i] < l[i + 1] < l[i + 2] or l[i] > l[i + 1] > l[i + 2]
            for i in range(n - 2)
        )
    )
)

n = int(input())
l = list(map(int, input().split()))
a = 0
for i in range(n - 2):
    p, q, r = l[i : i + 3]
    if p < q < r or r < q < p:
        a += 1
print(a)


Input:
N = int(input())

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

ans, s = 0, 0

d = {0:1}

for i in A:

    s += i

    ans += d.get(s, 0)

    d[s] = d.get(s, 0) + 1

print(ans)

#!/usr/bin/env python3

from collections import defaultdict

N = int(input())

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

d = defaultdict(int)

d[0] = 1

s, ans = 0, 0

for a in A:

    s += a

    ans += d[s]

    d[s] += 1

print (ans)

N = int(input())
A = list(map(int, input().split()))
ans, s = 0, 0
d = {0: 1}
for i in A:
    s += i
    ans += d.get(s, 0)
    d[s] = d.get(s, 0) + 1
print(ans)

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

N = int(input())
A = list(map(int, input().split()))
d = defaultdict(int)
d[0] = 1
s, ans = 0, 0
for a in A:
    s += a
    ans += d[s]
    d[s] += 1
print(ans)

-N = int(input())
+#!/usr/bin/env python3
+from collections import defaultdict
+
+N = int(input())
-ans, s = 0, 0
-d = {0: 1}
-for i in A:
-    s += i
-    ans += d.get(s, 0)
-    d[s] = d.get(s, 0) + 1
+d = defaultdict(int)
+d[0] = 1
+s, ans = 0, 0
+for a in A:
+    s += a
+    ans += d[s]
+    d[s] += 1


Input:
N = int(input())

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

dp = [[0 for i in range(3)] for j in range(N+1)]

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

    for j in range(3):

        for k in range(3):

            if j != k:

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

print((max(dp[N][0], dp[N][1], dp[N][2])))

N = int(input())

dp = [[0 for i in range(3)] for j in range(N+1)]

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

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

    for j in range(3):

        for k in range(3):

            if j != k:

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

print((max(dp[N][0], dp[N][1], dp[N][2])))

N = int(input())
l = [list(map(int, input().split())) for _ in range(N)]
dp = [[0 for i in range(3)] for j in range(N + 1)]
for i in range(1, N + 1):
    for j in range(3):
        for k in range(3):
            if j != k:
                dp[i][j] = max(dp[i][j], dp[i - 1][k] + l[i - 1][k])
print((max(dp[N][0], dp[N][1], dp[N][2])))

N = int(input())
dp = [[0 for i in range(3)] for j in range(N + 1)]
for i in range(1, N + 1):
    hapiness = list(map(int, input().split()))
    for j in range(3):
        for k in range(3):
            if j != k:
                dp[i][j] = max(dp[i][j], dp[i - 1][k] + hapiness[k])
print((max(dp[N][0], dp[N][1], dp[N][2])))

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

+    hapiness = list(map(int, input().split()))

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


Input:
import sys

input = sys.stdin.readline

def main():

    ans = 0

    n = int(input())

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

    l = [0]*n

    for i in range(n):

        l[o[i]-1] = i+1

    for i in range(len(l)):

        if  i != len(l)-1:

            print("{} ".format(l[i]), end='')

        else:

            print(l[i])

if __name__ == '__main__':

    main()

import sys

input = sys.stdin.readline

def main():

    ans = 0

    n = int(input())

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

    l = [0]*n

    for i in range(n):

        l[o[i]-1] = i+1

    print((" ".join(map(str,l))))

if __name__ == '__main__':

    main()

import sys

input = sys.stdin.readline

def main():
    ans = 0
    n = int(input())
    o = list(map(int, input().split()))
    l = [0] * n
    for i in range(n):
        l[o[i] - 1] = i + 1
    for i in range(len(l)):
        if i != len(l) - 1:
            print("{} ".format(l[i]), end="")
        else:
            print(l[i])

if __name__ == "__main__":
    main()

import sys

input = sys.stdin.readline

def main():
    ans = 0
    n = int(input())
    o = list(map(int, input().split()))
    l = [0] * n
    for i in range(n):
        l[o[i] - 1] = i + 1
    print((" ".join(map(str, l))))

if __name__ == "__main__":
    main()

-            print("{} ".format(l[i]), end="")


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

taste = [L+i-1 for i in range(1,N+1)]

if taste[-1] < 0:

  print((sum(taste) + min([abs(x) for x in taste])))

else:

  print((sum(taste) - min([abs(x) for x in taste])))

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

taste = [L+i-1 for i in range(1, N+1)]

if 0 in taste:

    select = 0

else:

    select_with_ind = min(enumerate(taste), key = lambda x: abs(x[1]))

    select = select_with_ind[1]

print((sum(taste) - select))

N, L = list(map(int, input().split()))
taste = [L + i - 1 for i in range(1, N + 1)]
if taste[-1] < 0:
    print((sum(taste) + min([abs(x) for x in taste])))
else:
    print((sum(taste) - min([abs(x) for x in taste])))

N, L = list(map(int, input().split()))
taste = [L + i - 1 for i in range(1, N + 1)]
if 0 in taste:
    select = 0
else:
    select_with_ind = min(enumerate(taste), key=lambda x: abs(x[1]))
    select = select_with_ind[1]
print((sum(taste) - select))

-    print((sum(taste) + min([abs(x) for x in taste])))

-    print((sum(taste) - min([abs(x) for x in taste])))

+    select_with_ind = min(enumerate(taste), key=lambda x: abs(x[1]))


Input:
# ABC090B - Palindromic Numbers

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

count = 0

for i in range(a, b + 1):

    lst = list(map(int, list(str(i))))

    if lst[0] == lst[4] and lst[1] == lst[3]:

        count += 1

print(count)

# ABC090B - Palindromic Numbers

def main():

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

    cnt = 0

    for i in range(a, b + 1):

        s = str(i)

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

            cnt += 1

    print(cnt)

if __name__ == "__main__":

    main()

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

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


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

dp = [0] * n

for i in range(m):

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

    dp[x - 1] += 1

    dp[y - 1] += 1

for i in range(n):

    print((dp[i]))

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

A = [0] * n

for i in range(m):

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

    A[a - 1] += 1

    A[b - 1] += 1

for i in range(n):

    print((A[i]))

-    x, y = list(map(int, input().split()))

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


Input:
import sys

sys.setrecursionlimit(2147483647)

INF=float("inf")

MOD=10**9+7

input=lambda :sys.stdin.readline().rstrip()

from collections import deque

def resolve():

    k=int(input())

    E=[[] for _ in range(k)]

    for i in range(k):

        E[i].append(((i+1)%k,1))

        E[i].append(((10*i)%k,0))

    # 0-1 BFS

    dist=[INF]*k

    dist[1]=0

    Q=deque([1])

    while(Q):

        v=Q.popleft()

        for nv,w in E[v]:

            if(dist[nv]<=dist[v]+w): continue

            dist[nv]=dist[v]+w

            if(w==0): Q.appendleft(nv)

            else: Q.append(nv)

    print((dist[0]+1))

resolve()

import sys

INF = 1 << 60

MOD = 10**9 + 7 # 998244353

sys.setrecursionlimit(2147483647)

input = lambda:sys.stdin.readline().rstrip()

from collections import deque

def resolve():

    k = int(input())

    dist = [INF] * k

    dist[1] = 1

    queue = deque([1])

    while queue:

        v = queue.pop()

        if dist[10 * v % k] > dist[v]:

            dist[10 * v % k] = dist[v]

            queue.appendleft(10 * v % k)

        if dist[(v + 1) % k] > dist[v] + 1:

            dist[(v + 1) % k] = dist[v] + 1

            queue.append((v + 1) % k)

    print((dist[0]))

resolve()

import sys

sys.setrecursionlimit(2147483647)
INF = float("inf")
MOD = 10**9 + 7
input = lambda: sys.stdin.readline().rstrip()
from collections import deque

def resolve():
    k = int(input())
    E = [[] for _ in range(k)]
    for i in range(k):
        E[i].append(((i + 1) % k, 1))
        E[i].append(((10 * i) % k, 0))
    # 0-1 BFS
    dist = [INF] * k
    dist[1] = 0
    Q = deque([1])
    while Q:
        v = Q.popleft()
        for nv, w in E[v]:
            if dist[nv] <= dist[v] + w:
                continue
            dist[nv] = dist[v] + w
            if w == 0:
                Q.appendleft(nv)
            else:
                Q.append(nv)
    print((dist[0] + 1))

resolve()

import sys

INF = 1 << 60
MOD = 10**9 + 7  # 998244353
sys.setrecursionlimit(2147483647)
input = lambda: sys.stdin.readline().rstrip()
from collections import deque

def resolve():
    k = int(input())
    dist = [INF] * k
    dist[1] = 1
    queue = deque([1])
    while queue:
        v = queue.pop()
        if dist[10 * v % k] > dist[v]:
            dist[10 * v % k] = dist[v]
            queue.appendleft(10 * v % k)
        if dist[(v + 1) % k] > dist[v] + 1:
            dist[(v + 1) % k] = dist[v] + 1
            queue.append((v + 1) % k)
    print((dist[0]))

resolve()

-            if dist[nv] <= dist[v] + w:

+            queue.appendleft(10 * v % k)


Input:
import math

n = int(input())

print((math.factorial(n) % (10**9 + 7)))

n = int(input())

ans = 1

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

    ans *= i

    ans %= 10**9 + 7

print(ans)

n = int(input())
ans = 1
for i in range(1, n + 1):
    ans *= i
    ans %= 10**9 + 7
print(ans)

-print((math.factorial(n) % (10**9 + 7)))


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

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

cums = [0]

cump = [0]

for a in src:

    cums.append(cums[-1] + a)

    cump.append(cump[-1] + max(0,a))

ans = 0

for i in range(N-K+1):

    tmp = cump[i]

    tmp += max(0, cums[i+K] - cums[i])

    tmp += cump[N] - cump[i+K]

    ans = max(tmp, ans)

print(ans)

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

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

cums = [0]

cums_p = [0]

for a in A:

    cums.append(cums[-1] + a)

    cums_p.append(cums_p[-1] + max(0,a))

ans = -float('inf')

for l in range(N-K+1):

    free = cums_p[l] + cums_p[-1] - cums_p[l+K]

    cont = cums[l+K] - cums[l]

    ans = max(ans, free, free+cont)

print(ans)

N, K = list(map(int, input().split()))
src = list(map(int, input().split()))
cums = [0]
cump = [0]
for a in src:
    cums.append(cums[-1] + a)
    cump.append(cump[-1] + max(0, a))
ans = 0
for i in range(N - K + 1):
    tmp = cump[i]
    tmp += max(0, cums[i + K] - cums[i])
    tmp += cump[N] - cump[i + K]
    ans = max(tmp, ans)
print(ans)

N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
cums = [0]
cums_p = [0]
for a in A:
    cums.append(cums[-1] + a)
    cums_p.append(cums_p[-1] + max(0, a))
ans = -float("inf")
for l in range(N - K + 1):
    free = cums_p[l] + cums_p[-1] - cums_p[l + K]
    cont = cums[l + K] - cums[l]
    ans = max(ans, free, free + cont)
print(ans)

-    tmp += max(0, cums[i + K] - cums[i])

+    cums_p.append(cums_p[-1] + max(0, a))

+    free = cums_p[l] + cums_p[-1] - cums_p[l + K]


Input:
def factorial(N):

    power_r = 1

    for n in range(2,N+1):

        power_r *= n

        power_r %= 10**9+7

    return power_r

if __name__ == '__main__':

    N = int(input())

    print((factorial(N)))

def factorial(N):

    power_r = 1

    for n in range(2,N+1):

        power_r = power_r*n % (10**9+7)

    return power_r

if __name__ == '__main__':

    N = int(input())

    print((factorial(N)))

def factorial(N):
    power_r = 1
    for n in range(2, N + 1):
        power_r *= n
        power_r %= 10**9 + 7
    return power_r

if __name__ == "__main__":
    N = int(input())
    print((factorial(N)))

def factorial(N):
    power_r = 1
    for n in range(2, N + 1):
        power_r = power_r * n % (10**9 + 7)
    return power_r

if __name__ == "__main__":
    N = int(input())
    print((factorial(N)))


Input:
import sys

K = int(input())

power = 7

SUM = 0

for i in range(1, 10 ** 6):

    SUM += power

    if SUM % K == 0:

        print(i)

        sys.exit()

    power *= 10

    power %= K

print((-1))

import sys

K = int(input())

L = 9 * K

if K % 7 == 0:

    L //= 7

power = 1

for i in range(1, 10 ** 6):

    power *= 10

    power %= L

    if power == 1:

        print(i)

        sys.exit()

print((-1))

import sys

K = int(input())
power = 7
SUM = 0
for i in range(1, 10**6):
    SUM += power
    if SUM % K == 0:
        print(i)
        sys.exit()
    power *= 10
    power %= K
print((-1))

import sys

K = int(input())
L = 9 * K
if K % 7 == 0:
    L //= 7
power = 1
for i in range(1, 10**6):
    power *= 10
    power %= L
    if power == 1:
        print(i)
        sys.exit()
print((-1))

-power = 7
-SUM = 0
+L = 9 * K
+if K % 7 == 0:
+    L //= 7
+power = 1
-    SUM += power
-    if SUM % K == 0:
+    power *= 10
+    power %= L
+    if power == 1:
-    power *= 10
-    power %= K


Input:
#E

from itertools import accumulate

from bisect import bisect_left

def main():

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

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

    A.sort()

    def count(k):

        cnt=0

        for a in A:

            cnt+=bisect_left(A,k-a)

        return cnt

    ok=0

    ng=10**10+1

    while ng-ok>1:

        mid=(ok+ng)//2

        if count(mid)<n**2-m:

            ok=mid

        else:

            ng=mid

    border=ok

    k=n**2-count(border)

    Acc=[0]+list(accumulate(A))

    s=Acc[-1]

    ans=0

    for a in A:

        idx=bisect_left(A,border-a)

        ans+=a*(n-idx)+(s-Acc[idx])

    ans-=border*(k-m)

    print(ans)

if __name__=='__main__':

    main()

from itertools import accumulate

from bisect import bisect_left

def main():

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

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

    A.sort()

    def count(k):

        cnt=0

        for a in A:

            cnt+=bisect_left(A,k-a)

        return cnt

    ok=0

    ng=2*10**5+1

    while ng-ok>1:

        mid=(ok+ng)//2

        if count(mid)<n**2-m:

            ok=mid

        else:

            ng=mid

    border=ok

    k=n**2-count(border)

    Acc=[0]+list(accumulate(A))

    s=Acc[-1]

    ans=0

    for a in A:

        idx=bisect_left(A,border-a)

        ans+=a*(n-idx)+(s-Acc[idx])

    ans-=border*(k-m)

    print(ans)

if __name__=='__main__':

    main()

# E
from itertools import accumulate
from bisect import bisect_left

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

    def count(k):
        cnt = 0
        for a in A:
            cnt += bisect_left(A, k - a)
        return cnt

    ok = 0
    ng = 10**10 + 1
    while ng - ok > 1:
        mid = (ok + ng) // 2
        if count(mid) < n**2 - m:
            ok = mid
        else:
            ng = mid
    border = ok
    k = n**2 - count(border)
    Acc = [0] + list(accumulate(A))
    s = Acc[-1]
    ans = 0
    for a in A:
        idx = bisect_left(A, border - a)
        ans += a * (n - idx) + (s - Acc[idx])
    ans -= border * (k - m)
    print(ans)

if __name__ == "__main__":
    main()

from itertools import accumulate
from bisect import bisect_left

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

    def count(k):
        cnt = 0
        for a in A:
            cnt += bisect_left(A, k - a)
        return cnt

    ok = 0
    ng = 2 * 10**5 + 1
    while ng - ok > 1:
        mid = (ok + ng) // 2
        if count(mid) < n**2 - m:
            ok = mid
        else:
            ng = mid
    border = ok
    k = n**2 - count(border)
    Acc = [0] + list(accumulate(A))
    s = Acc[-1]
    ans = 0
    for a in A:
        idx = bisect_left(A, border - a)
        ans += a * (n - idx) + (s - Acc[idx])
    ans -= border * (k - m)
    print(ans)

if __name__ == "__main__":
    main()


Input:
import sys

input = sys.stdin.readline

n = int(input())

v = [[0]+[]*(n+1) for i in range(n+1)]

for i in range(n-1):

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

    v[a].append([b,c])

    v[b].append([a,c])

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

l = [k]

while l:

    now = l.pop()

    for i in v[now][1:]:

        if v[i[0]][0] == 0:

            v[i[0]][0] = i[1]+v[now][0]

            l.append(i[0])

for i in range(q):

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

    print((v[x][0]+v[y][0]))

import sys

def main():

    input = sys.stdin.readline

    n = int(input())

    v = [[0]+[]*(n+1) for i in range(n+1)]

    for i in range(n-1):

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

        v[a].append([b,c])

        v[b].append([a,c])

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

    l = [k]

    while l:

        now = l.pop()

        for i in v[now][1:]:

            if v[i[0]][0] == 0:

                v[i[0]][0] = i[1]+v[now][0]

                l.append(i[0])

    for i in range(q):

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

        print((v[x][0]+v[y][0]))

if __name__ == '__main__':

    main()

import sys

input = sys.stdin.readline
n = int(input())
v = [[0] + [] * (n + 1) for i in range(n + 1)]
for i in range(n - 1):
    a, b, c = list(map(int, input().split()))
    v[a].append([b, c])
    v[b].append([a, c])
q, k = list(map(int, input().split()))
l = [k]
while l:
    now = l.pop()
    for i in v[now][1:]:
        if v[i[0]][0] == 0:
            v[i[0]][0] = i[1] + v[now][0]
            l.append(i[0])
for i in range(q):
    x, y = list(map(int, input().split()))
    print((v[x][0] + v[y][0]))

import sys

def main():
    input = sys.stdin.readline
    n = int(input())
    v = [[0] + [] * (n + 1) for i in range(n + 1)]
    for i in range(n - 1):
        a, b, c = list(map(int, input().split()))
        v[a].append([b, c])
        v[b].append([a, c])
    q, k = list(map(int, input().split()))
    l = [k]
    while l:
        now = l.pop()
        for i in v[now][1:]:
            if v[i[0]][0] == 0:
                v[i[0]][0] = i[1] + v[now][0]
                l.append(i[0])
    for i in range(q):
        x, y = list(map(int, input().split()))
        print((v[x][0] + v[y][0]))

if __name__ == "__main__":
    main()

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

-    x, y = list(map(int, input().split()))

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

+    q, k = list(map(int, input().split()))

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


Input:
from functools import reduce

from itertools import product

N = int(input())

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

ans = 0

for t in product([-1, 0, 1], repeat=N):

    prod = reduce(lambda x, y: x*y, [a + t[i] for i, a in enumerate(A)])

    if prod % 2 == 0: ans += 1

print(ans)

N = int(input())

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

evens = 0

for a in A:

    if a % 2 == 0: evens += 1

ans = 3**N - 2**evens

print(ans)

from functools import reduce
from itertools import product

N = int(input())
(*A,) = list(map(int, input().split()))
ans = 0
for t in product([-1, 0, 1], repeat=N):
    prod = reduce(lambda x, y: x * y, [a + t[i] for i, a in enumerate(A)])
    if prod % 2 == 0:
        ans += 1
print(ans)

N = int(input())
(*A,) = list(map(int, input().split()))
evens = 0
for a in A:
    if a % 2 == 0:
        evens += 1
ans = 3**N - 2**evens
print(ans)

-for t in product([-1, 0, 1], repeat=N):

-    prod = reduce(lambda x, y: x * y, [a + t[i] for i, a in enumerate(A)])


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

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

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

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

low = 200001

for i in range(m):

    f = xyc[i][0] - 1

    d = xyc[i][1] - 1

    if low >= dr[f]+wa[d]-xyc[i][2]:

        low = dr[f]+wa[d]-xyc[i][2]

dr.sort()

wa.sort()

if low >= (dr[0] + wa[0]):

    print((dr[0] + wa[0]))

else:

    print(low)

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

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

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

low = min(al)+min(bl)

x = [0] * m

y = [0] * m

c = [0] * m

for i in range(m):

    x[i],y[i],c[i] = list(map(int, input().split()))

    x[i] -= 1

    y[i] -= 1

for i in range(m):

    low = min(low,al[x[i]]+bl[y[i]]-c[i])

print(low)

a, b, m = list(map(int, input().split()))
dr = list(map(int, input().split()))
wa = list(map(int, input().split()))
xyc = [list(map(int, input().split())) for i in range(m)]
low = 200001
for i in range(m):
    f = xyc[i][0] - 1
    d = xyc[i][1] - 1
    if low >= dr[f] + wa[d] - xyc[i][2]:
        low = dr[f] + wa[d] - xyc[i][2]
dr.sort()
wa.sort()
if low >= (dr[0] + wa[0]):
    print((dr[0] + wa[0]))
else:
    print(low)

a, b, m = list(map(int, input().split()))
al = list(map(int, input().split()))
bl = list(map(int, input().split()))
low = min(al) + min(bl)
x = [0] * m
y = [0] * m
c = [0] * m
for i in range(m):
    x[i], y[i], c[i] = list(map(int, input().split()))
    x[i] -= 1
    y[i] -= 1
for i in range(m):
    low = min(low, al[x[i]] + bl[y[i]] - c[i])
print(low)

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

-    if low >= dr[f] + wa[d] - xyc[i][2]:

-        low = dr[f] + wa[d] - xyc[i][2]

+    x[i], y[i], c[i] = list(map(int, input().split()))

+    low = min(low, al[x[i]] + bl[y[i]] - c[i])


Input:
l, r=list(map(int, input().split()))

if r-l>672:

	p=0

else:

	p=2019

	for i in range(l, r):

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

			p=min(p, (((i%2019)*(j%2019))%2019))

			if not p:

				break

		if not p:

			break

print(p)

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

if r-l>672:

	p=0

else:

	p=2019

	for i in range(l, r):

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

			p=min(p, (i*j%2019))

			if not p:

				break

		if not p:

			break

print(p)

l, r = list(map(int, input().split()))
if r - l > 672:
    p = 0
else:
    p = 2019
    for i in range(l, r):
        for j in range(i + 1, r + 1):
            p = min(p, (((i % 2019) * (j % 2019)) % 2019))
            if not p:
                break
        if not p:
            break
print(p)

l, r = list(map(int, input().split()))
if r - l > 672:
    p = 0
else:
    p = 2019
    for i in range(l, r):
        for j in range(i + 1, r + 1):
            p = min(p, (i * j % 2019))
            if not p:
                break
        if not p:
            break
print(p)


Input:
a,b,c,x,y = list(map(int,input().split()))

price = 10**10

for k in range(10**5+1):

    re = 2*c*k + max(0,x-k)*a + max(0,y-k)*b

    price = min(re,price)

print(price)

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

a1 = a*x + b*y

a2 = max(x,y) * 2*c

if y >= x:

    a3 = 2*c*x + (y-x)*b

else:

    a3 = 2*c*y + (x-y)*a

print((min(a1,a2,a3)))

a, b, c, x, y = list(map(int, input().split()))
price = 10**10
for k in range(10**5 + 1):
    re = 2 * c * k + max(0, x - k) * a + max(0, y - k) * b
    price = min(re, price)
print(price)

a, b, c, x, y = list(map(int, input().split()))
a1 = a * x + b * y
a2 = max(x, y) * 2 * c
if y >= x:
    a3 = 2 * c * x + (y - x) * b
else:
    a3 = 2 * c * y + (x - y) * a
print((min(a1, a2, a3)))


Input:
import math

print((math.factorial(int(input()))%(10**9+7)))

ans=1

n=int(input())

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

    ans*=i

    ans=ans%(10**9+7)

print(ans)

import math

print((math.factorial(int(input())) % (10**9 + 7)))

ans = 1
n = int(input())
for i in range(1, n + 1):
    ans *= i
    ans = ans % (10**9 + 7)
print(ans)

-print((math.factorial(int(input())) % (10**9 + 7)))


Input:
import sys

input = sys.stdin.readline

n = int(input())

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

cnt = 0

for b, a in ab:

    cnt += a

    if cnt > b:

        print('No')

        break

else:

    print('Yes')

n = int(input())

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

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

t = 0

for a, b in ab:

    t += a

    if t > b:

        print('No')

        break

else:

    print('Yes')

import sys

input = sys.stdin.readline
n = int(input())
ab = sorted([list(map(int, input().split()))[::-1] for _ in range(n)])
cnt = 0
for b, a in ab:
    cnt += a
    if cnt > b:
        print("No")
        break
else:
    print("Yes")

n = int(input())
ab = [list(map(int, input().split())) for _ in range(n)]
ab = sorted(ab, key=lambda x: x[1])
t = 0
for a, b in ab:
    t += a
    if t > b:
        print("No")
        break
else:
    print("Yes")

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

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


Input:
from collections import Counter

N = int(input())

div = []

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

    while i != 1:

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

            while i%d==0:

                i = i//d

                div.append(d)

C = Counter(div).most_common()

Ans = 1

for k,v in C:

    Ans = Ans*(v+1) % (10**9+7)

print(Ans)

from collections import defaultdict

N = int(input())

F = [True]*(N+1)

F[0]=F[1]=False

P = []

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

    if F[i]==True:

        P.append(i)

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

            F[j]=False

dic = defaultdict(int)

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

    for p in P:

        while i%p==0:

            dic[p] += 1

            i = i//p

        if i==1:

            break

ans = 1

modulo = 10**9+7

for v in list(dic.values()):

    ans *= (v+1)

    ans %= modulo

print(ans)

from collections import Counter

N = int(input())
div = []
for i in range(2, N + 1):
    while i != 1:
        for d in range(2, i + 1):
            while i % d == 0:
                i = i // d
                div.append(d)
C = Counter(div).most_common()
Ans = 1
for k, v in C:
    Ans = Ans * (v + 1) % (10**9 + 7)
print(Ans)

from collections import defaultdict

N = int(input())
F = [True] * (N + 1)
F[0] = F[1] = False
P = []
for i in range(2, N + 1):
    if F[i] == True:
        P.append(i)
        for j in range(i * 2, N + 1, i):
            F[j] = False
dic = defaultdict(int)
for i in range(2, N + 1):
    for p in P:
        while i % p == 0:
            dic[p] += 1
            i = i // p
        if i == 1:
            break
ans = 1
modulo = 10**9 + 7
for v in list(dic.values()):
    ans *= v + 1
    ans %= modulo
print(ans)

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


Input:
from collections import deque

from copy import deepcopy, copy

dy = [-1, 0, 0, 1]

dx = [0, -1, 1, 0]

N = 3

def g(i, j, a):

    t = a // (10 ** j) % 10

    return a - t * (10 ** j) + t * (10 ** i)

def MAIN():

    m = {8:{7, 5}, 7:{8, 6, 4}, 6:{7, 3}, 5:{8, 4, 2}, 4:{7, 5, 3, 1}, 3:{6, 4, 0}, 2:{5, 1}, 1:{4, 2, 0}, 0:{3, 1}}

    MAP = "".join(input().replace(" ", "") for _ in range(N))

    start = 8 - MAP.find("0")

    MAP = int(MAP)

    goal = ('1', '2', '3', '4', '5', '6', '7', '8', '0')

    goal = 123456780

    dp = deque([(0, start, MAP)])

    LOG = {MAP}

    while dp:

        cnt, yx, M = dp.popleft()

        if M == goal:

            print(cnt)

            break

        cnt += 1

        for nyx in m[yx]:

            CM = g(yx, nyx, M)

            if not CM in LOG:

                dp.append((cnt, nyx, CM))

                LOG.add(CM)

MAIN()

from collections import deque

from copy import deepcopy, copy

N = 3

def g(i, j, a):

    if i > j:

        i, j = j, i

    return a[:i] + a[j] + a[i + 1:j] + a[i] + a[j + 1:]

def MAIN():

    m = {8:{7, 5}, 7:{8, 6, 4}, 6:{7, 3}, 5:{8, 4, 2}, 4:{7, 5, 3, 1}, 3:{6, 4, 0}, 2:{5, 1}, 1:{4, 2, 0}, 0:{3, 1}}

    MAP = "".join(input().replace(" ", "") for _ in range(N))

    start = MAP.find("0")

    goal = "123456780"

    dp = deque([(0, start, MAP)])

    LOG = {MAP}

    while dp:

        cnt, yx, M = dp.popleft()

        if M == goal:

            print(cnt)

            break

        cnt += 1

        for nyx in m[yx]:

            CM = g(yx, nyx, M)

            if not CM in LOG:

                dp.append((cnt, nyx, CM))

                LOG.add(CM)

MAIN()

from collections import deque
from copy import deepcopy, copy

N = 3

def g(i, j, a):
    if i > j:
        i, j = j, i
    return a[:i] + a[j] + a[i + 1 : j] + a[i] + a[j + 1 :]

def MAIN():
    m = {
        8: {7, 5},
        7: {8, 6, 4},
        6: {7, 3},
        5: {8, 4, 2},
        4: {7, 5, 3, 1},
        3: {6, 4, 0},
        2: {5, 1},
        1: {4, 2, 0},
        0: {3, 1},
    }
    MAP = "".join(input().replace(" ", "") for _ in range(N))
    start = MAP.find("0")
    goal = "123456780"
    dp = deque([(0, start, MAP)])
    LOG = {MAP}
    while dp:
        cnt, yx, M = dp.popleft()
        if M == goal:
            print(cnt)
            break
        cnt += 1
        for nyx in m[yx]:
            CM = g(yx, nyx, M)
            if not CM in LOG:
                dp.append((cnt, nyx, CM))
                LOG.add(CM)

MAIN()


Input:
# vim: fileencoding=utf-8

def main():

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

    c = 0

    for i in range(a, b + 1):

        s = str(i)

        r = "".join(reversed(list(s)))

        if s == r:

            c += 1

    print(c)

if __name__ == "__main__":

    main()

# vim: fileencoding=utf-8

def main():

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

    c = 0

    for i in range(a, b + 1):

        #     s = str(i)

        #     r = "".join(reversed(list(s)))

        #     if s == r:

        #         c += 1

        if (i % 10) == (i // 10000 % 10) and (i // 10 % 10) == (i // 1000 % 10):

            c += 1

    print(c)

if __name__ == "__main__":

    main()

+        #     r = "".join(reversed(list(s)))


Input:
A, B, C, X, Y = list(map(int, input().split()))

ans = float('inf')

for i in range(10 ** 5 + 1):

    ans = min(ans, A * max(X - i, 0) + B * max(Y - i, 0) + 2 * C * i)

print(ans)

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

# ans = float('inf')

# for i in range(10 ** 5 + 1):

#     ans = min(ans, A * max(X - i, 0) + B * max(Y - i, 0) + 2 * C * i)

# print(ans)

min_xy = min(X, Y)

max_xy = max(X, Y)

ans1 = 2 * C * min_xy + A * (X - min_xy) + B * (Y - min_xy)

ans2 = A * X + B * Y

ans3 = 2 * C * max_xy

print((min(ans1, ans2, ans3)))

A, B, C, X, Y = list(map(int, input().split()))
ans = float("inf")
for i in range(10**5 + 1):
    ans = min(ans, A * max(X - i, 0) + B * max(Y - i, 0) + 2 * C * i)
print(ans)

-    ans = min(ans, A * max(X - i, 0) + B * max(Y - i, 0) + 2 * C * i)

+#     ans = min(ans, A * max(X - i, 0) + B * max(Y - i, 0) + 2 * C * i)

+ans1 = 2 * C * min_xy + A * (X - min_xy) + B * (Y - min_xy)


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

l=[0 for i in range(k+1)]

for i in range(m):

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

  l[a-1]+=1;l[s]-=1

ans=0

f=0

for j in range(k):

  l[j]+=f

  f=l[j]

print((len([1 for i in l if i==m])))

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

table=[0]*(n+2)

for i in range(m):

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

    table[l]+=1

    table[r+1]-=1

from itertools import accumulate

from collections import Counter as co

var=co((accumulate(table)))

if m not in var:print((0))

else:print((var[m]))

k, m = list(map(int, input().split()))
l = [0 for i in range(k + 1)]
for i in range(m):
    a, s = list(map(int, input().split()))
    l[a - 1] += 1
    l[s] -= 1
ans = 0
f = 0
for j in range(k):
    l[j] += f
    f = l[j]
print((len([1 for i in l if i == m])))

n, m = list(map(int, input().split()))
table = [0] * (n + 2)
for i in range(m):
    l, r = list(map(int, input().split()))
    table[l] += 1
    table[r + 1] -= 1
from itertools import accumulate
from collections import Counter as co

var = co((accumulate(table)))
if m not in var:
    print((0))
else:
    print((var[m]))

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

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


Input:
N = int(input())

count = [[0 for _ in range(9)] for _ in range(9)]

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

    if str(i)[0] != "0" and str(i)[-1] != "0":

        count[int(str(i)[0]) - 1][int(str(i)[-1]) - 1] += 1

ans = 0

for i in range(0, 9):

    for k in range(0, 9):

        ans += count[i][k] * count[k][i]

print(ans)

N = int(input())

nums = [0 for i in range(100)]

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

    i = str(i)

    nums[int(i[0] + i[-1])] += 1

ans = 0

for i in range(1, 10):

    for j in range(i, 10):

        i = str(i)

        j = str(j)

        if i != j:

            ans += nums[int(i + j)] * nums[int(j + i)] * 2

        else:

            n = nums[int(i + j)]

            ans += n * (n - 1)

            ans += n

print(ans)

-count = [[0 for _ in range(9)] for _ in range(9)]

-        ans += count[i][k] * count[k][i]

+            ans += nums[int(i + j)] * nums[int(j + i)] * 2


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

import sys

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

def list2d(a, b, c): return [[c] * b for i in range(a)]

def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]

def ceil(x, y=1): return int(-(-x // y))

def INT(): return int(input())

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

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

def Yes(): print('Yes')

def No(): print('No')

def YES(): print('YES')

def NO(): print('NO')

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

MOD = 10 ** 9 + 7

X,Y,Z,K=MAP()

A=sorted(LIST(), reverse=True)

B=sorted(LIST(), reverse=True)

C=sorted(LIST(), reverse=True)

ABC=[]

for i in range(X):

    for j in range(Y):

        if (i+1)*(j+1)>K:

            break

        for k in range(Z):

            if (i+1)*(j+1)*(k+1)>K:

                break

            ABC.append(A[i]+B[j]+C[k])

ABC.sort(reverse=True)

for i in range(K):

    print((ABC[i]))

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

import sys

from heapq import heappush, heappop

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

def list2d(a, b, c): return [[c] * b for i in range(a)]

def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]

def ceil(x, y=1): return int(-(-x // y))

def INT(): return int(input())

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

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

def Yes(): print('Yes')

def No(): print('No')

def YES(): print('YES')

def NO(): print('NO')

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

MOD = 10 ** 9 + 7

X,Y,Z,K=MAP()

A=sorted(LIST(), reverse=True)

B=sorted(LIST(), reverse=True)

C=sorted(LIST(), reverse=True)

que=[]

heappush(que, (-(A[0]+B[0]+C[0]), 0, 0, 0))

S={(0,0,0)}

for i in range(K):

    ans=heappop(que)

    print((-ans[0]))

    a,b,c=ans[1:]

    if a+1<X and (a+1,b,c) not in S:

        heappush(que, (-(A[a+1]+B[b]+C[c]), a+1, b, c))

        S.add((a+1,b,c))

    if b+1<Y and (a,b+1,c) not in S:

        heappush(que, (-(A[a]+B[b+1]+C[c]), a, b+1, c))

        S.add((a,b+1,c))

    if c+1<Z and (a,b,c+1) not in S:

        heappush(que, (-(A[a]+B[b]+C[c+1]), a, b, c+1))

        S.add((a,b,c+1))

# -*- coding: utf-8 -*-
import sys

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

def list2d(a, b, c):
    return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
    return [[[d] * c for j in range(b)] for i in range(a)]

def ceil(x, y=1):
    return int(-(-x // y))

def INT():
    return int(input())

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

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

def Yes():
    print("Yes")

def No():
    print("No")

def YES():
    print("YES")

def NO():
    print("NO")

sys.setrecursionlimit(10**9)
INF = float("inf")
MOD = 10**9 + 7
X, Y, Z, K = MAP()
A = sorted(LIST(), reverse=True)
B = sorted(LIST(), reverse=True)
C = sorted(LIST(), reverse=True)
ABC = []
for i in range(X):
    for j in range(Y):
        if (i + 1) * (j + 1) > K:
            break
        for k in range(Z):
            if (i + 1) * (j + 1) * (k + 1) > K:
                break
            ABC.append(A[i] + B[j] + C[k])
ABC.sort(reverse=True)
for i in range(K):
    print((ABC[i]))

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

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

def list2d(a, b, c):
    return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
    return [[[d] * c for j in range(b)] for i in range(a)]

def ceil(x, y=1):
    return int(-(-x // y))

def INT():
    return int(input())

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

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

def Yes():
    print("Yes")

def No():
    print("No")

def YES():
    print("YES")

def NO():
    print("NO")

sys.setrecursionlimit(10**9)
INF = float("inf")
MOD = 10**9 + 7
X, Y, Z, K = MAP()
A = sorted(LIST(), reverse=True)
B = sorted(LIST(), reverse=True)
C = sorted(LIST(), reverse=True)
que = []
heappush(que, (-(A[0] + B[0] + C[0]), 0, 0, 0))
S = {(0, 0, 0)}
for i in range(K):
    ans = heappop(que)
    print((-ans[0]))
    a, b, c = ans[1:]
    if a + 1 < X and (a + 1, b, c) not in S:
        heappush(que, (-(A[a + 1] + B[b] + C[c]), a + 1, b, c))
        S.add((a + 1, b, c))
    if b + 1 < Y and (a, b + 1, c) not in S:
        heappush(que, (-(A[a] + B[b + 1] + C[c]), a, b + 1, c))
        S.add((a, b + 1, c))
    if c + 1 < Z and (a, b, c + 1) not in S:
        heappush(que, (-(A[a] + B[b] + C[c + 1]), a, b, c + 1))
        S.add((a, b, c + 1))

-            ABC.append(A[i] + B[j] + C[k])

+    if a + 1 < X and (a + 1, b, c) not in S:

+    if b + 1 < Y and (a, b + 1, c) not in S:

+    if c + 1 < Z and (a, b, c + 1) not in S:


Input:
#!/usr/bin/env python3

import sys

sys.setrecursionlimit(10**6)

INF = 10 ** 9 + 1  # sys.maxsize # float("inf")

MOD = 10 ** 9 + 7

def floor_sum(n, m, a, b):

    ret = 0

    if a >= m:

        ret += (n - 1) * n * (a // m) // 2

        a %= m

    if b >= m:

        ret += n * (b // m)

        b %= m

    y_max = (a * n + b) // m

    x_max = y_max * m - b

    if y_max == 0:

        return ret

    ret += (n - (x_max + a - 1) // a) * y_max

    ret += floor_sum(y_max, a, m, (a - x_max % a) % a)

    return ret

def debug(*x):

    print(*x, file=sys.stderr)

def solve(SOLVE_PARAMS):

    pass

def main():

    # parse input

    T = int(input())

    for _t in range(T):

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

        print(floor_sum(N, M, A, B))

# tests

T1 = """

5

4 10 6 3

6 5 4 3

1 1 0 0

31415 92653 58979 32384

1000000000 1000000000 999999999 999999999

"""

TEST_T1 = """

>>> as_input(T1)

>>> main()

3

13

0

314095480

499999999500000000

"""

def _test():

    import doctest

    doctest.testmod()

    g = globals()

    for k in sorted(g):

        if k.startswith("TEST_"):

            doctest.run_docstring_examples(g[k], g, name=k)

def as_input(s):

    "use in test, use given string as input file"

    import io

    f = io.StringIO(s.strip())

    g = globals()

    g["input"] = lambda: bytes(f.readline(), "ascii")

    g["read"] = lambda: bytes(f.read(), "ascii")

input = sys.stdin.buffer.readline

read = sys.stdin.buffer.read

if sys.argv[-1] == "-t":

    print("testing")

    _test()

    sys.exit()

main()

#!/usr/bin/env python3

import sys

sys.setrecursionlimit(10**6)

INF = 10 ** 9 + 1  # sys.maxsize # float("inf")

MOD = 10 ** 9 + 7

def floor_sum_1(n, m, a, b):

    ret = 0

    if a >= m:

        ret += (n - 1) * n * (a // m) // 2

        a %= m

    if b >= m:

        ret += n * (b // m)

        b %= m

    y_max = (a * n + b) // m

    x_max = y_max * m - b

    if y_max == 0:

        return ret

    ret += (n - (x_max + a - 1) // a) * y_max

    ret += floor_sum(y_max, a, m, (a - x_max % a) % a)

    return ret

def floor_sum(n, m, a, b):

    ret = 0

    while True:

        if a >= m:

            ret += (n - 1) * n * (a // m) // 2

            a %= m

        if b >= m:

            ret += n * (b // m)

            b %= m

        y_max = (a * n + b) // m

        x_max = y_max * m - b

        if y_max == 0:

            return ret

        ret += (n - (x_max + a - 1) // a) * y_max

        n = y_max

        m, a, b = a, m, (a - x_max % a) % a

def debug(*x):

    print(*x, file=sys.stderr)

def solve(SOLVE_PARAMS):

    pass

def main():

    # parse input

    T = int(input())

    for _t in range(T):

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

        print(floor_sum(N, M, A, B))

# tests

T1 = """

5

4 10 6 3

6 5 4 3

1 1 0 0

31415 92653 58979 32384

1000000000 1000000000 999999999 999999999

"""

TEST_T1 = """

>>> as_input(T1)

>>> main()

3

13

0

314095480

499999999500000000

"""

def _test():

    import doctest

    doctest.testmod()

    g = globals()

    for k in sorted(g):

        if k.startswith("TEST_"):

            doctest.run_docstring_examples(g[k], g, name=k)

def as_input(s):

    "use in test, use given string as input file"

    import io

    f = io.StringIO(s.strip())

    g = globals()

    g["input"] = lambda: bytes(f.readline(), "ascii")

    g["read"] = lambda: bytes(f.read(), "ascii")

input = sys.stdin.buffer.readline

read = sys.stdin.buffer.read

if sys.argv[-1] == "-t":

    print("testing")

    _test()

    sys.exit()

main()

#!/usr/bin/env python3
import sys

sys.setrecursionlimit(10**6)
INF = 10**9 + 1  # sys.maxsize # float("inf")
MOD = 10**9 + 7

def floor_sum(n, m, a, b):
    ret = 0
    if a >= m:
        ret += (n - 1) * n * (a // m) // 2
        a %= m
    if b >= m:
        ret += n * (b // m)
        b %= m
    y_max = (a * n + b) // m
    x_max = y_max * m - b
    if y_max == 0:
        return ret
    ret += (n - (x_max + a - 1) // a) * y_max
    ret += floor_sum(y_max, a, m, (a - x_max % a) % a)
    return ret

def debug(*x):
    print(*x, file=sys.stderr)

def solve(SOLVE_PARAMS):
    pass

def main():
    # parse input
    T = int(input())
    for _t in range(T):
        N, M, A, B = map(int, input().split())
        print(floor_sum(N, M, A, B))

# tests
T1 = """
5
4 10 6 3
6 5 4 3
1 1 0 0
31415 92653 58979 32384
1000000000 1000000000 999999999 999999999
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
3
13
0
314095480
499999999500000000
"""

def _test():
    import doctest

    doctest.testmod()
    g = globals()
    for k in sorted(g):
        if k.startswith("TEST_"):
            doctest.run_docstring_examples(g[k], g, name=k)

def as_input(s):
    "use in test, use given string as input file"
    import io

    f = io.StringIO(s.strip())
    g = globals()
    g["input"] = lambda: bytes(f.readline(), "ascii")
    g["read"] = lambda: bytes(f.read(), "ascii")

input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
if sys.argv[-1] == "-t":
    print("testing")
    _test()
    sys.exit()
main()

#!/usr/bin/env python3
import sys

sys.setrecursionlimit(10**6)
INF = 10**9 + 1  # sys.maxsize # float("inf")
MOD = 10**9 + 7

def floor_sum_1(n, m, a, b):
    ret = 0
    if a >= m:
        ret += (n - 1) * n * (a // m) // 2
        a %= m
    if b >= m:
        ret += n * (b // m)
        b %= m
    y_max = (a * n + b) // m
    x_max = y_max * m - b
    if y_max == 0:
        return ret
    ret += (n - (x_max + a - 1) // a) * y_max
    ret += floor_sum(y_max, a, m, (a - x_max % a) % a)
    return ret

def floor_sum(n, m, a, b):
    ret = 0
    while True:
        if a >= m:
            ret += (n - 1) * n * (a // m) // 2
            a %= m
        if b >= m:
            ret += n * (b // m)
            b %= m
        y_max = (a * n + b) // m
        x_max = y_max * m - b
        if y_max == 0:
            return ret
        ret += (n - (x_max + a - 1) // a) * y_max
        n = y_max
        m, a, b = a, m, (a - x_max % a) % a

def debug(*x):
    print(*x, file=sys.stderr)

def solve(SOLVE_PARAMS):
    pass

def main():
    # parse input
    T = int(input())
    for _t in range(T):
        N, M, A, B = map(int, input().split())
        print(floor_sum(N, M, A, B))

# tests
T1 = """
5
4 10 6 3
6 5 4 3
1 1 0 0
31415 92653 58979 32384
1000000000 1000000000 999999999 999999999
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
3
13
0
314095480
499999999500000000
"""

def _test():
    import doctest

    doctest.testmod()
    g = globals()
    for k in sorted(g):
        if k.startswith("TEST_"):
            doctest.run_docstring_examples(g[k], g, name=k)

def as_input(s):
    "use in test, use given string as input file"
    import io

    f = io.StringIO(s.strip())
    g = globals()
    g["input"] = lambda: bytes(f.readline(), "ascii")
    g["read"] = lambda: bytes(f.read(), "ascii")

input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
if sys.argv[-1] == "-t":
    print("testing")
    _test()
    sys.exit()
main()

+        m, a, b = a, m, (a - x_max % a) % a


Input:
import math

N = int(input())

ans = 10**12

for i in range(1,10**6+1):

  j = math.ceil(N/(i+1))

  if (1+i)*j == N:

    ans = min(i+j-1,ans)

  if i == 10**6 and ans == 10**12:

    ans = N-1

    break

print(ans)

N = int(input())

ans = 10**12

for i in range(1,10**6+1):

  j = N//i

  if i*j == N:

    ans = min(i+j-2,ans)

  if i == 10**6 and ans == 10**12:

    ans = N-1

    break

print(ans)

import math

N = int(input())
ans = 10**12
for i in range(1, 10**6 + 1):
    j = math.ceil(N / (i + 1))
    if (1 + i) * j == N:
        ans = min(i + j - 1, ans)
    if i == 10**6 and ans == 10**12:
        ans = N - 1
        break
print(ans)

N = int(input())
ans = 10**12
for i in range(1, 10**6 + 1):
    j = N // i
    if i * j == N:
        ans = min(i + j - 2, ans)
    if i == 10**6 and ans == 10**12:
        ans = N - 1
        break
print(ans)

-import math
-    j = math.ceil(N / (i + 1))
-    if (1 + i) * j == N:
-        ans = min(i + j - 1, ans)
+    j = N // i
+    if i * j == N:
+        ans = min(i + j - 2, ans)


Input:
mod = 998244353

N = int(input())

X = []

for _ in range(N):

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

    X.append((x, x + d))

X = sorted(X, key = lambda x: x[0])

L = [(0, -(10**9+1), 10**9+1)]

P = [-1] * (N+1)

for i, (x, y) in enumerate(X):

    while L[-1][2] <= y:

        if L[-1][2] > x and P[i+1] < 0:

            P[i+1] = L[-1][0]

        L.pop()

    if P[i+1] < 0:

        P[i+1] = L[-1][0]

    L.append((i+1, x, y))

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

for i, p in enumerate(P):

    if p >= 0:

        C[p].append(i)

Y = [1] * (N+1)

for i in range(N+1)[::-1]:

    s = 1

    for j in C[i]:

        s = s * (Y[j] + 1) % mod

    Y[i] = s

print((Y[0]))

import sys

input = sys.stdin.readline

mod = 998244353

N = int(input())

X = []

for _ in range(N):

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

    X.append((x, x + d))

X = sorted(X, key = lambda x: x[0])

L = [(0, -(10**9+1), 10**9+1)]

P = [-1] * (N+1)

for i, (x, y) in enumerate(X):

    while L[-1][2] <= y:

        if L[-1][2] > x and P[i+1] < 0:

            P[i+1] = L[-1][0]

        L.pop()

    if P[i+1] < 0:

        P[i+1] = L[-1][0]

    L.append((i+1, x, y))

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

for i, p in enumerate(P):

    if p >= 0:

        C[p].append(i)

Y = [1] * (N+1)

for i in range(N+1)[::-1]:

    s = 1

    for j in C[i]:

        s = s * (Y[j] + 1) % mod

    Y[i] = s

print((Y[0]))

import sys

input = sys.stdin.readline
mod = 998244353
N = int(input())
X = []
for _ in range(N):
    x, d = list(map(int, input().split()))
    X.append((x, x + d))
X = sorted(X, key=lambda x: x[0])
L = [(0, -(10**9 + 1), 10**9 + 1)]
P = [-1] * (N + 1)
for i, (x, y) in enumerate(X):
    while L[-1][2] <= y:
        if L[-1][2] > x and P[i + 1] < 0:
            P[i + 1] = L[-1][0]
        L.pop()
    if P[i + 1] < 0:
        P[i + 1] = L[-1][0]
    L.append((i + 1, x, y))
C = [[] for _ in range(N + 1)]
for i, p in enumerate(P):
    if p >= 0:
        C[p].append(i)
Y = [1] * (N + 1)
for i in range(N + 1)[::-1]:
    s = 1
    for j in C[i]:
        s = s * (Y[j] + 1) % mod
    Y[i] = s
print((Y[0]))

+import sys
+
+input = sys.stdin.readline


Input: print((sum(si != ti for si, ti in zip(input(), input()))))

print((sum(a!=b for a,b in zip(*open(0)))))

-print((sum(si != ti for si, ti in zip(input(), input()))))

+print((sum(a != b for a, b in zip(*open(0)))))