Problem:


Score: 400 points

Problem Statement

The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:

The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.

The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.

The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.

Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

1 \leq K \leq \min(3 \ 000, X \times Y \times Z)

1 \leq A_i \leq 10 \ 000 \ 000 \ 000

1 \leq B_i \leq 10 \ 000 \ 000 \ 000

1 \leq C_i \leq 10 \ 000 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

Output

Print K lines. The i-th line should contain the i-th value stated in the problem statement.

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:

(A_2, B_2, C_2): 6 + 5 + 8 = 19

(A_1, B_2, C_2): 4 + 5 + 8 = 17

(A_2, B_1, C_2): 6 + 1 + 8 = 15

(A_2, B_2, C_1): 6 + 5 + 3 = 14

(A_1, B_1, C_2): 4 + 1 + 8 = 13

(A_1, B_2, C_1): 4 + 5 + 3 = 12

(A_2, B_1, C_1): 6 + 1 + 3 = 10

(A_1, B_1, C_1): 4 + 1 + 3 = 8

Sample Input 2

3 3 3 5
1 10 100
2 20 200
1 10 100

Sample Output 2

400
310
310
301
301

There may be multiple combinations of cakes with the same sum of the deliciousness. For example, in this test case, the sum of A_1, B_3, C_3 and the sum of A_3, B_3, C_1 are both 301.
However, they are different ways of choosing cakes, so 301 occurs twice in the output.

Sample Input 3

10 10 10 20
7467038376 5724769290 292794712 2843504496 3381970101 8402252870 249131806 6310293640 6690322794 6082257488
1873977926 2576529623 1144842195 1379118507 6003234687 4925540914 3902539811 3326692703 484657758 2877436338
4975681328 8974383988 2882263257 7690203955 514305523 6679823484 4263279310 585966808 3752282379 620585736

Sample Output 3

23379871545
22444657051
22302177772
22095691512
21667941469
21366963278
21287912315
21279176669
21160477018
21085311041
21059876163
21017997739
20703329561
20702387965
20590247696
20383761436
20343962175
20254073196
20210218542
20150096547

Note that the input or output may not fit into a 32-bit integer type.



Sample input:
2 2 2 8
4 6
1 5
3 8


Sample output:
19
17
15
14
13
12
10
8

Submission status: Accepted

Solution code:
x,y,z,k=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=list(map(int,input().split()))

from heapq import heappop,heappush,heapify
def main1(a,b,c,k):
  ans=[]
  for x in a:
    for y in b:
      ans.append(-x-y)
  ans.sort()
  ans=ans[:k] if len(ans)>=k else ans+[0]*(k-len(ans))
  ans1=[]
  for z in c:
    for xy in ans:
      heappush(ans1,xy-z)
  for _ in range(k):
    print(-heappop(ans1))
def main2(a,b,c,k):
  a.sort(reverse=True)
  b.sort(reverse=True)
  c.sort(reverse=True)
  al=[]
  for i,x in enumerate(a):
    for j,y in enumerate(b):
      for l,z in enumerate(c):
        if (i+1)*(j+1)*(l+1)<=k:
          al.append(x+y+z)
        else:
          break
  al.sort()
  for _ in range(k):
    print(al.pop())

main2(a,b,c,k)

Submission status: Accepted

Solution code:
x,y,z,k=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=list(map(int,input().split()))

from heapq import heappop,heappush,heapify
def main1(a,b,c,k):
  ans=[]
  for x in a:
    for y in b:
      ans.append(-x-y)
  ans.sort()
  ans=ans[:k] if len(ans)>=k else ans+[0]*(k-len(ans))
  ans1=[]
  for z in c:
    for xy in ans:
      heappush(ans1,xy-z)
  for _ in range(k):
    print(-heappop(ans1))
main1(a,b,c,k)

Submission status: Accepted

Solution code:
from heapq import *
x,y,z,k = map(int,input().split())
A,B,C = [list(map(int,input().split())) for n in range(3)]
D = nlargest(k,(a+b for a in A for b in B))
E = nlargest(k,(d+c for d in D for c in C))
print("\n".join(map(str,E)))

Submission status: Accepted

Solution code:
import heapq
from collections import defaultdict
x, y, z, K = map(int, input().split())
a = sorted(list(map(int, input().split())))[::-1]
b = sorted(list(map(int, input().split())))[::-1]
c = sorted(list(map(int, input().split())))[::-1]

used = defaultdict(bool)
pq = [(-(a[0] + b[0] + c[0]), 0, 0, 0)]
used[(0, 0, 0)] = True
heapq.heapify(pq)

for _ in range(K):
    d, i, j, k = heapq.heappop(pq)
    print(-d)
    if i + 1 < x and not used[(i + 1, j, k)]:
        heapq.heappush(pq, (-(a[i + 1] + b[j] + c[k]), i + 1, j, k))
        used[(i + 1, j, k)] = True
    if j + 1 < y and not used[(i, j + 1, k)]:
        heapq.heappush(pq, (-(a[i] + b[j + 1] + c[k]), i, j + 1, k))
        used[(i, j + 1, k)] = True
    if k + 1 < z and not used[(i, j, k + 1)]:
        heapq.heappush(pq, (-(a[i] + b[j] + c[k + 1]), i, j, k + 1))
        used[(i, j, k + 1)] = True

Submission status: Accepted

Solution code:
x, y, z, K = map(int, input().split())
a = sorted(list(map(int, input().split())))[::-1]
b = sorted(list(map(int, input().split())))[::-1]
c = sorted(list(map(int, input().split())))[::-1]

ans = []
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
            ans.append(a[i] + b[j] + c[k])
ans = sorted(ans)[::-1]
print(*ans[:K])

Submission status: Accepted

Solution code:
x, y, z, K = map(int, input().split())
a = sorted(list(map(int, input().split())))[::-1]
b = sorted(list(map(int, input().split())))[::-1]
c = sorted(list(map(int, input().split())))[::-1]


ans = []
for i in range(x):
    for j in range(y):
        if i * j > K:
            break
        for k in range(z):
            if i * j * k > K:
                break
            ans.append(a[i] + b[j] + c[k])
ans = sorted(ans)[::-1]
for i in range(K):
    print(ans[i])

Submission status: Accepted

Solution code:
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり


X,Y,Z,K = MI()
A,B,C = LI(),LI(),LI()
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)

ANS = []
for i in range(X):
    if i >= K:
        break
    a = A[i]
    for j in range(Y):
        if i*j >= K:
            break
        b = B[j]
        for k in range(Z):
            if i*j*k >= K:
                break
            c = C[k]
            ANS.append(a+b+c)

ANS.sort(reverse=True)
print(*ANS[:K],sep='\n')

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

x,y,z,k = inpl()
a = inpl()
b = inpl()
c = inpl()
ab = []
for s in a:
    for t in b:
        ab.append(s+t)
ab.sort(reverse = True)
ab = ab[:3000]
abc = []
for s in ab:
    for j in c:
        abc.append(s+j)
abc.sort(reverse = True)
print(*abc[:k])

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

X, Y, Z, K = mapint()
As = list(mapint())
Bs = list(mapint())
Cs = list(mapint())
As.sort(reverse=True)
Bs.sort(reverse=True)
Cs.sort(reverse=True)

from heapq import heappop, heappush
Q = []
heappush(Q, (-(As[0]+Bs[0]+Cs[0]), 0, 0, 0))
s = set()
for _ in range(K):
    v, a, b, c = heappop(Q)
    print(-v)
    if a+1<X and not (a+1, b, c) in s:
        s.add((a+1, b, c))
        heappush(Q, (-(As[a+1]+Bs[b]+Cs[c]), a+1, b, c))
    if b+1<Y and not (a, b+1, c) in s:
        s.add((a, b+1, c))
        heappush(Q, (-(As[a]+Bs[b+1]+Cs[c]), a, b+1, c))
    if c+1<Z and not (a, b, c+1) in s:
        s.add((a, b, c+1))
        heappush(Q, (-(As[a]+Bs[b]+Cs[c+1]), a, b, c+1))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
X,Y,Z,K = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
C = list(map(int,input().split()))

AB = []
AC = []
BC = []
for a in A:
    for b in B:
        AB.append(a+b)
    for c in C:
        AC.append(a+c)
for b in B:
    for c in C:
        BC.append(b+c)
AB.sort(reverse=True)
AC.sort(reverse=True)
BC.sort(reverse=True)

import heapq
hq = []
for x in AB[:K]:
    for c in C:
        heapq.heappush(hq, -x-c)
for x in BC[:K]:
    for a in A:
        heapq.heappush(hq, -x-a)
for x in AC[:K]:
    for b in B:
        heapq.heappush(hq, -x-b)

ans = []
for _ in range(K):
    ans.append(-heapq.heappop(hq))
    heapq.heappop(hq)
    heapq.heappop(hq)
print(*ans, sep='\n')

Submission status: Accepted

Solution code:
x, y, z, k = map(int, input().split())
alst = list(map(int, input().split()))
blst = list(map(int, input().split()))
clst = list(map(int, input().split()))
alst.sort(reverse = True)
blst.sort(reverse = True)
clst.sort(reverse = True)
ans = []
for i in range(x):
    for j in range(y):
        if i * j > k:
            break
        for l in range(z):
            if i * j * l > k:
                break
            ans.append(alst[i] + blst[j] + clst[l])
ans.sort(reverse = True)
print(*ans[:k], sep = "\n")

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし


X,Y,Z,K = MI()
A,B,C = LI(),LI(),LI()
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)

ANS = []
for i in range(X):
    if i >= K:
        break
    a = A[i]
    for j in range(Y):
        if i*j >= K:
            break
        b = B[j]
        for k in range(Z):
            if i*j*k >= K:
                break
            c = C[k]
            ANS.append(a+b+c)

ANS.sort(reverse=True)
print(*ANS[:K],sep='\n')

Submission status: Accepted

Solution code:
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)

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)

Submission status: Accepted

Solution code:
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")

Submission status: Accepted

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
ceil = math.ceil
x,y,z,k = ma()
A = lma()
B=lma()
C=lma()
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
i,j,m = 0,0,0
h=[(-A[i]-B[j]-C[m],i,j,m)]
cnt=0
d=collections.defaultdict(lambda:True)
while cnt<k:
    ans,i,j,m=hq.heappop(h)
    print(-ans)
    if i+1<x and d[(i+1,j,m)]:
        hq.heappush(h,(-A[i+1]-B[j]-C[m],i+1,j,m))
        d[(i+1,j,m)]=False
    if j+1<y and d[(i,j++1,m)]:
        hq.heappush(h,(-A[i]-B[j+1]-C[m],i,j+1,m))
        d[(i,j+1,m)]=False
    if m+1<z and d[(i,j,m+1)]:
        hq.heappush(h,(-A[i]-B[j]-C[m+1],i,j,m+1))
        d[(i,j,m+1)]=False
    cnt+=1

Submission status: Accepted

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
ceil = math.ceil
x,y,z,k = ma()
A = lma()
B=lma()
C=lma()
AB = [a+b for a in A for b in B]
AB.sort(reverse=True)
C.sort(reverse=True)
ans=[]
iab=min(k,x*y)
ic=min(k,z)
for i in range(ic):
    for j in range(iab):
        ans.append(AB[j]+C[i])
ans.sort(reverse=True)
for i in range(k):
    print(ans[i])

Submission status: Accepted

Solution code:
import heapq as hq
x,y,z,K = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
C = list(map(int,input().split()))
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
abc = [(-(A[0]+B[0]+C[0]), 0,0,0)]
used = set((0,0,0))
while K > 0:
    K -= 1
    p,i,j,k = hq.heappop(abc)
    print(-p)
    for a,b,c in [(i+1,j,k), (i,j+1,k), (i,j,k+1)]:
        if a < x and b < y and c < z and (a,b,c) not in used:
            used.add((a,b,c))
            hq.heappush(abc, (-(A[a]+B[b]+C[c]), a,b,c))

Submission status: Accepted

Solution code:
import heapq as hq
x,y,z,k = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
C = list(map(int,input().split()))
ab = []
for a in A:
    for b in B:
        hq.heappush(ab, -a-b)
abc = []
cnt = 0
while cnt < k and ab:
    cnt += 1
    a = hq.heappop(ab)
    for b in C:
        hq.heappush(abc, a-b)
cnt = 0
while cnt < k:
    print(-hq.heappop(abc))
    cnt += 1

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


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


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(X, Y, Z, K, A, B, C):
    q = []

    for a in A:
        for b in B:
            if len(q) < K:
                heapq.heappush(q, a+b)
            else:
                heapq.heappushpop(q, a+b)

    qq = []
    for c in C:
        for d in q:
            if len(qq) < K:
                heapq.heappush(qq, d+c)
            else:
                heapq.heappushpop(qq, d+c)

    qq.sort(reverse=True)
    return qq

def main():
    X, Y, Z, K = read_int_n()
    A = read_int_n()
    B = read_int_n()
    C = read_int_n()
    print(*slv(X, Y, Z, K, A, B, C), sep='\n')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


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


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(X, Y, Z, K, A, B, C):
    q = []
    A.sort(reverse=True)
    B.sort(reverse=True)
    C.sort(reverse=True)
    if len(A) > K:
        A = A[:K]
    if len(B) > K:
        B = B[:K]
    if len(C) > K:
        C = C[:K]

    for a in A:
        for b in B:
            heapq.heappush(q, a+b)
            if len(q) > K:
                heapq.heappop(q)

    qq = []
    for c in C:
        for d in q:
            heapq.heappush(qq, d+c)
            if len(qq) > K:
                heapq.heappop(qq)
    qq.sort(reverse=True)
    return qq

def main():
    X, Y, Z, K = read_int_n()
    A = read_int_n()
    B = read_int_n()
    C = read_int_n()
    print(*slv(X, Y, Z, K, A, B, C), sep='\n')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


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


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(X, Y, Z, K, A, B, C):
    q = []

    for a in A:
        for b in B:
            heapq.heappush(q, a+b)
            if len(q) > K:
                heapq.heappop(q)

    qq = []
    for c in C:
        for d in q:
            heapq.heappush(qq, d+c)
            if len(qq) > K:
                heapq.heappop(qq)
    qq.sort(reverse=True)
    return qq

def main():
    X, Y, Z, K = read_int_n()
    A = read_int_n()
    B = read_int_n()
    C = read_int_n()
    print(*slv(X, Y, Z, K, A, B, C), sep='\n')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
x,y,z,k=map(int,input().split())
a=sorted(list(map(int,input().split())))[::-1]
b=sorted(list(map(int,input().split())))[::-1]
c=sorted(list(map(int,input().split())))[::-1]
d=[]
for i in a:
  for j in b:
    d+=[i+j]
ans=[]
d=sorted(d)[::-1][:k]
for i in c:
  for j in d:
    ans+=[i+j]
print(*sorted(ans)[::-1][:k],sep='\n')

Submission status: Accepted

Solution code:
from heapq import heappop, heappush

X, Y, Z, K = map(int, input().split())

# heahqで最大値を扱いたいのでマイナスにしておく
A = sorted(list(map(lambda x: -int(x), input().split())))
B = sorted(list(map(lambda x: -int(x), input().split())))
C = sorted(list(map(lambda x: -int(x), input().split())))

#　プライオリティキュー
#　heapqの要素はタプルに出来る
hq = []
u = (A[0] + B[0] + C[0], 0, 0, 0)
heappush(hq, u)

# 同じものを複数回追加しないようにチェック
visited = set()
visited.add(u)

for i in range(K):
    x, i, j, k = heappop(hq)
    print(-x)
    # A, B, Cについての次の値をpush
    if i + 1 <= X - 1:
        next_i = (A[i + 1] + B[j] + C[k], i + 1, j, k)
        if next_i not in visited:
            heappush(hq, next_i)
            visited.add(next_i)
    if j + 1 <= Y - 1:
        next_j = (A[i] + B[j + 1] + C[k], i, j + 1, k)
        if next_j not in visited:
            heappush(hq, next_j)
            visited.add(next_j)
    if k + 1 <= Z - 1:
        next_k = (A[i] + B[j] + C[k + 1], i, j, k + 1)
        if next_k not in visited:
            heappush(hq, next_k)
            visited.add(next_k)

Submission status: Accepted

Solution code:
X, Y, Z, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = list(map(int, input().split()))

# A+Bの上位K個
tmp = []
for a in A:
    for b in B:
        tmp.append(a + b)
tmp.sort(reverse=True)
tmp = tmp[:K]

ans = []
for ab in tmp:
    for c in C:
        ans.append(ab + c)
ans.sort(reverse=True)

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

Submission status: Accepted

Solution code:
import os
import sys
from atexit import register
from io import BytesIO

import heapq

sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
raw_input = lambda: sys.stdin.readline().rstrip('\r\n')

x,y,z,k = (int(x) for x in input().split())
a = sorted((int(i) for i in input().split()), reverse=True)
b = sorted((int(i) for i in input().split()), reverse=True)
c = sorted((int(i) for i in input().split()), reverse=True)


h = []
heapq.heappush(h, (-a[0]-b[0]-c[0],(0,0,0)))
visited = dict()
cnt = 0
while True:
    cost, node = heapq.heappop(h)
    if visited.get(node, False):
        continue
    visited[node] = True
    cnt += 1
    print(-cost)
    if cnt == k:
        break
    if node[0] + 1 != x:
        heapq.heappush(h,(cost+a[node[0]] - a[node[0] + 1], (node[0]+1, node[1], node[2])))
    if node[1] + 1 != y:
        heapq.heappush(h,(cost+b[node[1]] - b[node[1] + 1], (node[0], node[1]+1, node[2])))
    if node[2] + 1 != z:
        heapq.heappush(h,(cost+c[node[2]] - c[node[2] + 1], (node[0], node[1], node[2]+1)))

Submission status: Accepted

Solution code:
X, Y, Z, K = map(int, input().split())

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

AB = []
for a in A:
  for b in B:
    AB.append(a+b)
    
AB.sort(reverse = True)

AB = AB[0:K]

C = list(map(int, input().split()))
ABC = []
for ab in AB:
  for c in C:
    ABC.append(ab+c)
    
ABC.sort(reverse = True)

for i in range(K):
  print(ABC[i])

Submission status: Accepted

Solution code:
from collections import deque
X, Y, Z, K = map(int, input().split())
A = sorted(list(map(int, input().split())), reverse=True)
B = sorted(list(map(int, input().split())), reverse=True)
C = sorted(list(map(int, input().split())), reverse=True)

A.append(-int(1e+100))
B.append(-int(1e+100))
C.append(-int(1e+100))

Aq = deque(A)
Bq = deque(B)
Ar = [Aq.popleft()]
Br = [Bq.popleft()]
maximum = min((len(A)-1) + (len(B)-1), 3001)
preA = Ar[0]
preB = Br[0]

while len(Ar) + len(Br) < maximum:
    if  Ar[0] - Aq[0] > Br[0] - Bq[0]:
        Br.append(Bq.popleft())
        preB = Br[-1]
    else:
        Ar.append(Aq.popleft())
        preA = Ar[-1]

AB = [Ar[i] + Br[j] for i in range(len(Ar)) for j in range(len(Br))]
AB = sorted(AB, reverse=True)

AB.append(-int(1e+15))

ABq = deque(AB)
Cq = deque(C)
ABr = [ABq.popleft()]
Cr = [Cq.popleft()]
maximum = min((len(AB)-1) + (len(C)-1), 3001)
preAB = ABr[0]
preC = Cr[0]
while len(ABr) + len(Cr) < maximum:
    if ABr[0] - ABq[0] > Cr[0] - Cq[0]:
        Cr.append(Cq.popleft())
        preC = Cr[-1]
    else:
        ABr.append(ABq.popleft())
        preAB = ABr[-1]

ABC = [ABr[i] + Cr[j] for i in range(len(ABr)) for j in range(len(Cr))]
ABC = sorted(ABC, reverse=True)

for i in range(K):
    print(ABC[i])

Submission status: Accepted

Solution code:
from collections import deque
X, Y, Z, K = map(int, input().split())
A = sorted(list(map(int, input().split())), reverse=True)
B = sorted(list(map(int, input().split())), reverse=True)
C = sorted(list(map(int, input().split())), reverse=True)

A.append(-int(1e+15))
B.append(-int(1e+15))
C.append(-int(1e+15))

Aq = deque(A)
Bq = deque(B)
Ar = [Aq.popleft()]
Br = [Bq.popleft()]
maximum = min((len(A)-1) + (len(B)-1), K+1)
preA = Ar[0]
preB = Br[0]

while len(Ar) + len(Br) < maximum:
    if  Ar[0] - Aq[0] > Br[0] - Bq[0]:
        Br.append(Bq.popleft())
        preB = Br[-1]
    else:
        Ar.append(Aq.popleft())
        preA = Ar[-1]

AB = [Ar[i] + Br[j] for i in range(len(Ar)) for j in range(len(Br))]
AB = sorted(AB, reverse=True)

AB.append(-int(1e+15))

ABq = deque(AB)
Cq = deque(C)
ABr = [ABq.popleft()]
Cr = [Cq.popleft()]
maximum = min((len(AB)-1) + (len(C)-1), K+1)
preAB = ABr[0]
preC = Cr[0]
while len(ABr) + len(Cr) < maximum:
    if ABr[0] - ABq[0] > Cr[0] - Cq[0]:
        Cr.append(Cq.popleft())
        preC = Cr[-1]
    else:
        ABr.append(ABq.popleft())
        preAB = ABr[-1]

ABC = [ABr[i] + Cr[j] for i in range(len(ABr)) for j in range(len(Cr))]
ABC = sorted(ABC, reverse=True)

for i in range(K):
    print(ABC[i])

Submission status: Accepted

Solution code:
# 解説を参考に作成

# import sys
# sys.setrecursionlimit(10 ** 6)
# import bisect
# from collections import deque
# from decorator import stop_watch
#
#
# @stop_watch
def solve(X, Y, Z, K, As, Bs, Cs):
    ABs = []
    for A in As:
        for B in Bs:
            ABs.append(A + B)
    ABs.sort(reverse=True)
    ABCs = []
    for i in range(min(X * Y, K)):
        AB = ABs[i]
        for C in Cs:
            ABCs.append(AB + C)
    ABCs.sort(reverse=True)
    for i in range(K):
        print(ABCs[i])


if __name__ == '__main__':
    # S = input()
    # N = int(input())
    X, Y, Z, K = map(int, input().split())
    As = [int(i) for i in input().split()]
    Bs = [int(i) for i in input().split()]
    Cs = [int(i) for i in input().split()]
    # import random
    # X, Y, Z, K = 1000,1000,1000,3000
    # As = [random.randint(1, 10 ** 10) for _ in range(X)]
    # Bs = [random.randint(1, 10 ** 10) for _ in range(Y)]
    # Cs = [random.randint(1, 10 ** 10) for _ in range(Z)]
    solve(X, Y, Z, K, As, Bs, Cs)