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.

Solution (Python):
x, y, z, k = list(map(int, input().split()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = list(map(int, input().split()))
import heapq
q = []
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
def val(i, j, k):
  return -(A[i] + B[j] + C[k])
heapq.heappush(q, (val(0,0,0), 0,0,0))
visited = set((0,0,0))
for _ in range(k):
  v, aa, bb, cc = heapq.heappop(q)
  print(-v)
  if aa + 1 < len(A) and (aa+1, bb, cc) not in visited:
    visited.add((aa+1, bb, cc))
    heapq.heappush(q, (val(aa+1, bb, cc), aa+1, bb, cc))
  if bb + 1 < len(B) and (aa, bb+1, cc) not in visited:
    visited.add((aa, bb+1, cc))
    heapq.heappush(q, (val(aa, bb+1, cc), aa, bb+1, cc))
  if cc + 1 < len(C) and (aa, bb, cc+1) not in visited:
    visited.add((aa, bb, cc+1))
    heapq.heappush(q, (val(aa, bb, cc+1), aa, bb, cc+1))

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [tuple(map(int, l.split())) for l in sys.stdin]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    x,y,z,k = LI()
    a = sorted(LI(), reverse=True)
    b = sorted(LI(), reverse=True)
    c = sorted(LI(), reverse=True)
    u = set()
    q = []
    heapq.heappush(q, (-(a[0]+b[0]+c[0]), 0,0,0))
    u.add((0,0,0))
    r = []
    for _ in range(k):
        t,ai,bi,ci = heapq.heappop(q)
        r.append(-t)
        if ai < x-1:
            nk = (ai+1,bi,ci)
            if nk not in u:
                heapq.heappush(q, (-(a[ai+1]+b[bi]+c[ci]), ai+1,bi,ci))
                u.add(nk)
        if bi < y-1:
            nk = (ai,bi+1,ci)
            if nk not in u:
                heapq.heappush(q, (-(a[ai]+b[bi+1]+c[ci]), ai,bi+1,ci))
                u.add(nk)
        if ci < z-1:
            nk = (ai,bi,ci+1)
            if nk not in u:
                heapq.heappush(q, (-(a[ai]+b[bi]+c[ci+1]), ai,bi,ci+1))
                u.add(nk)

    return '\n'.join(map(str, r))

print(main())

Solution (Python):
from collections import defaultdict
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()))
A.sort(reverse = 1)
B.sort(reverse = 1)
C.sort(reverse = 1)
dic = {}
for x in range(1, min(X + 1, K + 1)):
    t = K // x + 1
    for y in range(1, min(Y + 1, t + 1)):
        s = t // y + 1
        for z in range(1, min(Z + 1, s + 1)):
            if (x, y, z) not in dic:
                dic[(x, y, z)] = A[x-1] + B[y-1] + C[z-1]
dic = sorted(dic.values(), reverse = 1)
for i in range(K):
    print(dic[i])

Solution (Python):
import heapq


class PriorityQueue:
    def __init__(self):
        self.__heap = []
        self.__count = 0

    def empty(self) -> bool:
        return self.__count == 0

    def dequeue(self):
        if self.empty():
            raise Exception('empty')
        self.__count -= 1
        return heapq.heappop(self.__heap)

    def enqueue(self, v):
        self.__count += 1
        heapq.heappush(self.__heap, v)

    def __len__(self):
        return self.__count


def cake123(X: int, Y: int, Z: int, K: int, A: list, B: list, C: list)->list:
    ret = [0] * K

    sA = sorted(-a for a in A)
    sB = sorted(-b for b in B)
    sC = sorted(-c for c in C)

    q = PriorityQueue()
    q.enqueue((sA[0] + sB[0] + sC[0], 0, 0, 0))

    used = {}

    k = 0
    while k < K:
        delicious, ai, bi, ci = q.dequeue()
        if -delicious in used and (ai, bi, ci) in used[-delicious]:
            continue

        used.setdefault(-delicious, set())
        used[-delicious].add((ai, bi, ci))

        ret[k] = -delicious
        k += 1

        if ai+1 < X:
            q.enqueue((sA[ai+1] + sB[bi] + sC[ci], ai+1, bi, ci))
        if bi+1 < Y:
            q.enqueue((sA[ai] + sB[bi+1] + sC[ci], ai, bi+1, ci))
        if ci+1 < Z:
            q.enqueue((sA[ai] + sB[bi] + sC[ci+1], ai, bi, ci+1))

    return ret


if __name__ == "__main__":
    X, Y, Z, K = map(int, input().split())
    A = [int(s) for s in input().split()]
    B = [int(s) for s in input().split()]
    C = [int(s) for s in input().split()]
    ans = cake123(X, Y, Z, K, A, B, C)
    for a in ans:
        print(a)

Solution (Python):
X,Y,Z,K = list(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)

ma,mb,mc = A[0],B[0],C[0]
sA = [a-ma for a in A] + [-10**15]
sB = [b-mb for b in B] + [-10**15]
sC = [c-mc for c in C] + [-10**15]

ia,ib,ic = 0,0,0
while min(10**5,(X)*(Y)*(Z)) > (ia+1)*(ib+1)*(ic+1):
    m = max(sA[ia+1],sB[ib+1],sC[ic+1])
    if ia < (X-1) and sA[ia+1] == m:
        ia = min(ia+1,X-1)
    if ib < (Y-1) and sB[ib+1] == m:
        ib = min(ib+1,Y-1)
    if ic < (Z-1) and sC[ic+1] == m:
        ic = min(ic+1,Z-1)
ans = []
for a in A[:ia+1]:
    for b in B[:ib+1]:
        for c in C[:ic+1]:
            ans.append(a+b+c)
ans.sort(reverse=True)
for out in ans[:K]:
    print(out)

Solution (Python):

import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)


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


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


def read_float():
    return float(input())


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


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


def read_str_n():
    return list(map(str, input().split()))


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


def mt(f):
    import time

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

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

    return wrap


@mt
def slv(A, B, C, K):
    A.sort(reverse=True)
    B.sort(reverse=True)
    C.sort(reverse=True)

    def s(i, j, k):
        return A[i] + B[j] + C[k]
    used = set()
    
    cand = []
    if 1 < len(A):
        heapq.heappush(cand, (-s(1, 0, 0), (1, 0, 0)))
        used.add((1, 0, 0))
    if 1 < len(B):
        heapq.heappush(cand, (-s(0, 1, 0), (0, 1, 0)))
        used.add((0, 1, 0))
    if 1 < len(C):
        heapq.heappush(cand, (-s(0, 0, 1), (0, 0, 1)))
        used.add((0, 0, 1))
    print(s(0, 0, 0))
    for _ in range(K-1):
        v, i = heapq.heappop(cand)
        print(-v)
        
        ti = (i[0]+1, i[1], i[2])
        if ti[0] < len(A) and ti not in used:
            heapq.heappush(cand, (-s(*ti), ti))
            used.add(ti)
        
        ti = (i[0], i[1]+1, i[2])
        if ti[1] < len(B) and ti not in used:
            heapq.heappush(cand, (-s(*ti), ti))
            used.add(ti)
        
        ti = (i[0], i[1], i[2]+1)
        if ti[2] < len(C) and ti not in used:
            heapq.heappush(cand, (-s(*ti), ti))
            used.add(ti)



def main():
    
    
    
    
    
    
    
    
    X, Y, Z, K = read_int_n()
    A = read_int_n()
    B = read_int_n()
    C = read_int_n()
    (slv(A, B, C, K))


if __name__ == '__main__':
    main()

Solution (Python):
import heapq

def solve():
    X=[0]*3
    X[0],X[1],X[2],K=map(int,input().split())
    A=[[] for i in range(3)]
    for i in range(3):
        A[i]=list(map(int,input().split()))
        A[i].sort(reverse=True)
    q = []
    heapq.heappush(q, (-A[0][0]-A[1][0]-A[2][0],0,0,0))
    m = [0 for i in range(3)]
    n = [0 for i in range(3)]
    done = set()
    done.add((0,0,0))
    for k in range(K):
        sc, n[0], n[1], n[2] = heapq.heappop(q)
        print(-sc)
        extend=False
        for i in range(3):
            if m[i] <= n[i] and m[i] < X[i] - 1:
                m[i] += 1
                extend=True
        
        if extend:
            for i0 in range(m[0]+1):
                for i1 in range(m[1]+1):
                    for i2 in range(m[2]+1):
                        if (i0,i1,i2) not in done:
                            done.add((i0,i1,i2))
                            heapq.heappush(q, (-A[0][i0]-A[1][i1]-A[2][i2],i0,i1,i2))
        

solve()

Solution (Python):
import heapq
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()))
inf = 10**18
a.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)
h = [0]*k
heapq.heapify(h)
for i in a:
    for j in b:
        cur = i+j
        t=0
        while t<z and h[0] < cur + c[t]:
            heapq.heappushpop(h, cur + c[t])
            t += 1
r = [heapq.heappop(h) for _ in range(k)]
for _ in range(k):
    print(r.pop())

Solution (Python):
from heapq import heappush,heappop

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]

h = []
heappush(h, (0, 0, 0, 0))
val = a[0] + b[0] + c[0]
searched = set()

cnt = 0
while cnt < k:
    cost, ia, ib, ic = heappop(h)
    if (ia, ib, ic) in searched:
        continue
    else:
        searched.add((ia, ib, ic))
        cnt += 1
    print(val - cost)
    if ia < x-1:
        heappush(h, (cost + a[ia] - a[ia+1], ia+1, ib, ic))
    if ib < y-1:
        heappush(h, (cost + b[ib] - b[ib+1], ia, ib+1, ic))
    if ic < z-1:
        heappush(h, (cost + c[ic] - c[ic+1], ia, ib, ic+1))

Solution (Python):
import heapq
X, Y, Z, K = map(int, input().split())
A = [int(a) for a in input().split()]
B = [int(b) for b in input().split()]
C = [int(c) for c in input().split()]
A.sort(reverse = True)
A.append(-10**20)
B.sort(reverse = True)
B.append(-10**20)
C.sort(reverse = True)
C.append(-10**20)

Q = []
heapq.heapify(Q)
heapq.heappush(Q, (-(A[0]+B[0]+C[0]), 0, 0, 0))
count = 0
fin = {}
while count < K:
    value, a, b, c = heapq.heappop(Q)
    if (a, b, c) not in fin:
        fin[(a, b, c)] = 1
        print(-value)
        heapq.heappush(Q, (-(A[a+1]+B[b]+C[c]), a+1, b, c))
        heapq.heappush(Q, (-(A[a]+B[b+1]+C[c]), a, b+1, c))
        heapq.heappush(Q, (-(A[a]+B[b]+C[c+1]), a, b, c+1))
        count += 1

Solution (Python):
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()))

tem = []

for i in range(x):
    for j in range(y):
        tem.append(a[i]+b[j])

tem.sort()
if(x*y > k):
    tem2 = tem[x*y-k-1:]
else:
    tem2 = tem
ans = []
for i in range(len(tem2)):
    for j in range(z):
        ans.append(tem2[i]+c[j])

ans.sort()
dd = len(tem2)*z
for i in list(reversed(range(dd-k,dd))):
    print(ans[i])

Solution (Python):
import heapq

class PrioritySet(object):
    def __init__(self):
        self.heap = []
        self.set = set()

    def add(self, pri, d):
        if not d in self.set:
            heapq.heappush(self.heap, (pri, d))
            self.set.add(d)

    def get(self):
        pri, d = heapq.heappop(self.heap)
        self.set.remove(d)
        return (pri, d)

X, Y, Z, K = map(int, input().split())
As = map(int, input().split())
As = sorted(As, reverse=True)
Bs = map(int, input().split())
Bs = sorted(Bs, reverse=True)
Cs = map(int, input().split())
Cs = sorted(Cs, reverse=True)

count = 0
h = PrioritySet()
h.add(-sum([As[0], Bs[0], Cs[0]]), (0, 0, 0))
while True:
    m, ii = h.get()
    ai, bi, ci = ii
    print(-m)
    count += 1
    if count == K:
        break

    if ai + 1 < len(As):
        h.add(-sum([As[ai+1], Bs[bi], Cs[ci]]), (ai+1, bi, ci))
    if bi + 1 < len(Bs):
        h.add(-sum([As[ai], Bs[bi+1], Cs[ci]]), (ai, bi+1, ci))
    if ci + 1 < len(Cs):
        h.add(-sum([As[ai], Bs[bi], Cs[ci+1]]), (ai, bi, ci+1))

Solution (Python):



from itertools import chain
from functools import reduce
from collections import OrderedDict, Counter, deque
import operator

IA = lambda: [int(x) for x in input().split()]

X,Y,Z,K = IA()
A, B, C = IA(), IA(), IA()
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
S = (A,B,C)

from heapq import *

inf = float('inf')
known = set()
q = []
c = (0,0,0)
v = sum([s[i] for s,i in zip(S, c)])
known.add(c)
heappush(q, (-v, c))
for _ in range(K):
    v, c = heappop(q)
    v = -v
    print(v)
    for i in range(3):
        n = c[i] + 1
        if len(S[i]) > n:
            nc = c[:i] + (n,) + c[i+1:]
            if nc not in known:
                known.add(nc)
                nv = sum([s[i] for s,i in zip(S, nc)])
                heappush(q, (-nv, nc))

Solution (Python):
import heapq
X, Y, Z, K = map(int, input().split())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
id = '0' * 9
v = A[0] + B[0] + C[0]
D = {}
D[id] = v
Q = [[-v, id]]
for i in range(K):
  q = heapq.heappop(Q)
  print(-q[0])
  ida = q[1][:3]
  idb = q[1][3:6]
  idc = q[1][6:9]
  if int(ida) < len(A) - 1:
    _ida = int(ida) + 1
    v = A[_ida] + B[int(idb)] + C[int(idc)]
    id = '{:03}'.format(_ida) + idb + idc
    if id not in D:
      D[id] = v
      heapq.heappush(Q, [-v, id])
  if int(idb) < len(B) - 1:
    _idb = int(idb) + 1
    v = A[int(ida)] + B[_idb] + C[int(idc)]
    id = ida + '{:03}'.format(_idb) + idc
    if id not in D:
      D[id] = v
      heapq.heappush(Q, [-v, id])
  if int(idc) < len(C) - 1:
    _idc = int(idc) + 1
    v = A[int(ida)] + B[int(idb)] + C[_idc]
    id = ida + idb + '{:03}'.format(_idc)
    if id not in D:
      D[id] = v
      heapq.heappush(Q, [-v, id])

Solution (Python):
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()))
c.sort(reverse=True)
ab = [0]*(x*y)
l = 0
for i in range(x):
    for j in range(y):
        ab[l] = a[i] + b[j]
        l += 1

ab.sort(reverse=True)
q = 0
i = 0
j = 0
ans = [0]*(k*k)
l = 0
for i in range(min(k,x*y)):
    for j in range(min(k,z)):
        ans[l] = ab[i] + c[j]
        l += 1

ans.sort(reverse=True)

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

Solution (Python):
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)
cand = []
for xi in range(x):
  if xi+1 > k:
    break
  for yi in range(y):
    if (xi+1)*(yi+1) > k:
        break
    for zi in range(z):
      if (xi+1)*(yi+1)*(zi+1) > k:
        break
      cand.append(a[xi]+b[yi]+c[zi])
cand.sort(reverse=True)
for i in range(k):
  print(cand[i])

Solution (Python):
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()
B.sort()
C.sort()
from heapq import heappush,heappop
ans=[]
data=[(-A[-1]-B[-1]-C[-1],X-1,Y-1,Z-1)]
visited={(X-1,Y-1,Z-1)}
while len(ans)<K:
    now=heappop(data)
    ans.append(-1*now[0])
    if now[1]>0 and (now[1]-1,now[2],now[3]) not in visited:
        nex=now[0]+A[now[1]]-A[now[1]-1]
        heappush(data,(nex,now[1]-1,now[2],now[3]))
        visited|={(now[1]-1,now[2],now[3])}
    if now[2]>0 and (now[1],now[2]-1,now[3]) not in visited:
        nex=now[0]+B[now[2]]-B[now[2]-1]
        heappush(data,(nex,now[1],now[2]-1,now[3]))
        visited|={(now[1],now[2]-1,now[3])}
    if now[3]>0 and (now[1],now[2],now[3]-1) not in visited:
        nex=now[0]+C[now[3]]-C[now[3]-1]
        heappush(data,(nex,now[1],now[2],now[3]-1))
        visited|={(now[1],now[2],now[3]-1)}
for i in range(K):
    print(ans[i])

Solution (Python):
import heapq


class PriorityQueue:
    def __init__(self):
        self.__heap = []
        self.__count = 0

    def empty(self) -> bool:
        return self.__count == 0

    def dequeue(self):
        if self.empty():
            raise Exception('empty')
        self.__count -= 1
        return heapq.heappop(self.__heap)

    def enqueue(self, v):
        self.__count += 1
        heapq.heappush(self.__heap, v)

    def __len__(self):
        return self.__count


def cake123(X: int, Y: int, Z: int, K: int, A: list, B: list, C: list)->list:
    ret = [0] * K

    sA = sorted(-a for a in A)
    sB = sorted(-b for b in B)
    sC = sorted(-c for c in C)

    q = PriorityQueue()
    q.enqueue((sA[0] + sB[0] + sC[0], 0, 0, 0))

    used = {}

    k = 0
    while k < K:
        delicious, ai, bi, ci = q.dequeue()
        if -delicious in used and (ai, bi, ci) in used[-delicious]:
            continue

        used.setdefault(-delicious, set())
        used[-delicious].add((ai, bi, ci))

        ret[k] = -delicious
        k += 1

        if ai+1 < X:
            q.enqueue((sA[ai+1] + sB[bi] + sC[ci], ai+1, bi, ci))
        if bi+1 < Y:
            q.enqueue((sA[ai] + sB[bi+1] + sC[ci], ai, bi+1, ci))
        if ci+1 < Z:
            q.enqueue((sA[ai] + sB[bi] + sC[ci+1], ai, bi, ci+1))
        if ai+1 < X and bi+1 < Y:
            q.enqueue((sA[ai+1] + sB[bi+1] + sC[ci], ai+1, bi+1, ci))
        if ai+1 < X and ci+1 < Z:
            q.enqueue((sA[ai+1] + sB[bi] + sC[ci+1], ai+1, bi, ci+1))
        if bi+1 < Y and ci+1 < Z:
            q.enqueue((sA[ai] + sB[bi+1] + sC[ci+1], ai, bi+1, ci+1))
        if ai+1 < X and bi+1 < Y and ci+1 < Z:
            q.enqueue((sA[ai+1] + sB[bi+1] + sC[ci+1], ai+1, bi+1, ci+1))

    return ret


if __name__ == "__main__":
    X, Y, Z, K = map(int, input().split())
    A = [int(s) for s in input().split()]
    B = [int(s) for s in input().split()]
    C = [int(s) for s in input().split()]
    ans = cake123(X, Y, Z, K, A, B, C)
    for a in ans:
        print(a)

Solution (Python):

from heapq import merge
from bisect import bisect
def inpl(): return list(map(int, input().split()))

X, Y, Z, K = inpl()
A = sorted(inpl())
B = sorted(inpl())
C = sorted(inpl(), reverse=True)

AB = [-1] * K
for a in A[::-1]:
    if AB[0] >= B[-1] + a:
        break
    tmp = [a + b for b in B[bisect(B, AB[0]-a):]][-K:]
    AB = list(merge(tmp, AB))[-K:]

ans = [-1] * K

for c in C:
    if ans[0] >= AB[-1] + c:
        break
    tmp = [ab + c for ab in AB[bisect(AB, ans[0]-c):]][-K:]
    ans = list(merge(ans, tmp))[-K:]

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

Solution (Python):
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 = []
for i in range(X):
    for j in range(Y):
        a.append(A[i] + B[j])
a.sort()
b = []
for i in range(min(3000, X * Y)):
    b.append(a[- i - 1])
c = []
for i in range(len(b)):
    for j in range(Z):
        c.append(b[i] + C[j])
c.sort()
for i in range(K):
    print(c[- i - 1])

Solution (Python):
x, y, z, k = map(int, input().split())
aaa = sorted(map(int, input().split()), reverse=True)
bbb = sorted(map(int, input().split()), reverse=True)
ccc = sorted(map(int, input().split()), reverse=True)
ma, mb, mc = aaa[0], bbb[0], ccc[0]
cakes = [(ma - a, 0) for a in aaa[1:]]
cakes += [(mb - b, 1) for b in bbb[1:]]
cakes += [(mc - c, 2) for c in ccc[1:]]
cakes.sort()

buf = [[ma], [mb], [mc]]
ans = [ma + mb + mc]

for d, i in cakes:
    if i == 0:
        a = aaa[len(buf[i])]
        if len(ans) == k and ans[-1] >= a + mb + mc:
            break
        buf[i].append(a)
        ans.extend(a + b + c for b in buf[1] for c in buf[2])
        ans.sort(reverse=True)
        ans = ans[:k]
    elif i == 1:
        b = bbb[len(buf[i])]
        if len(ans) == k and ans[-1] >= ma + b + mc:
            break
        buf[i].append(b)
        ans.extend(a + b + c for a in buf[0] for c in buf[2])
        ans.sort(reverse=True)
        ans = ans[:k]
    else:
        c = ccc[len(buf[i])]
        if len(ans) == k and ans[-1] >= ma + mb + c:
            break
        buf[i].append(c)
        ans.extend(a + b + c for a in buf[0] for b in buf[1])
        ans.sort(reverse=True)
        ans = ans[:k]

print('\n'.join(map(str, ans)))

Solution (Python):

from sys import stdin
import heapq

import sys
sys.setrecursionlimit(10**6)


s_in = lambda: stdin.readline()[:-1]  
d_in = lambda: int(stdin.readline())  
ds_in = lambda: list(map(int, stdin.readline().split()))  

X, Y, Z, K = ds_in()
A_list = ds_in()
B_list = ds_in()
C_list = ds_in()

A_list.sort(reverse=True)
B_list.sort(reverse=True)
C_list.sort(reverse=True)


def search(cand, searched):
    if len(searched) > K-1:
        exit()
    current = searched[-1][1]
    cand1 = (current[0]+1, current[1], current[2])
    cand2 = (current[0], current[1]+1, current[2])
    cand3 = (current[0], current[1], current[2]+1)
    if cand1[0] < len(A_list):
        val = A_list[cand1[0]] + B_list[cand1[1]] + C_list[cand1[2]]
        if (-val, cand1) not in cand:
            heapq.heappush(cand, (-val, cand1))
    if cand2[1] < len(B_list):
        val = A_list[cand2[0]] + B_list[cand2[1]] + C_list[cand2[2]]
        if (-val, cand2) not in cand:
            heapq.heappush(cand, (-val, cand2))
    if cand3[2] < len(C_list):
        val = A_list[cand3[0]] + B_list[cand3[1]] + C_list[cand3[2]]
        if (-val, cand3) not in cand:
            heapq.heappush(cand, (-val, cand3))
    next_ = heapq.heappop(cand)
    print(-next_[0])
    searched.append(next_)
    
    
    search(cand=cand, searched=searched)


searched = [(-(A_list[0] + B_list[0] + C_list[0]), (0, 0, 0))]
cand = []
print(-searched[0][0])
search(cand=cand, searched=searched)

Solution (Python):
import heapq, collections
X, Y, Z, K = [int(_) for _ in input().split()]
A, B, C = [
    sorted([int(_) for _ in input().split()], reverse=True) for _ in range(3)
]
H = [[-A[0] - B[0] - C[0], 0, 0, 0]]
heapq.heapify(H)
memo = collections.defaultdict(
    lambda: collections.defaultdict(lambda: collections.defaultdict(int)))
for _ in range(K):
    v, a, b, c = heapq.heappop(H)
    print(-v)
    for x, y, z in [[a + 1, b, c], [a, b + 1, c], [a, b, c + 1]]:
        if x < X and y < Y and z < Z and memo[x][y][z] == 0:
            heapq.heappush(H, [-A[x] - B[y] - C[z], x, y, z])
            memo[x][y][z] = 1

Solution (Python):

import sys


def solve(X: int, Y: int, Z: int, K: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    AB = []
    for a in A:
        for b in B:
            AB.append(a + b)
    AB.sort(reverse=True)
    C.sort(reverse=True)
    ret = []
    idx = [0] * Z
    for i in range(K):
        tmp = -1
        cur = -1
        for j in range(Z):
            if idx[j] < len(AB) and C[j] + AB[idx[j]] > tmp:
                tmp = C[j] + AB[idx[j]]
                cur = j
        ret.append(tmp)
        idx[cur] += 1
    for r in ret:
        print(r)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    X = int(next(tokens))  
    Y = int(next(tokens))  
    Z = int(next(tokens))  
    K = int(next(tokens))  
    A = [ int(next(tokens)) for _ in range(X) ]  
    B = [ int(next(tokens)) for _ in range(Y) ]  
    C = [ int(next(tokens)) for _ in range(Z) ]  
    solve(X, Y, Z, K, A, B, C)

if __name__ == '__main__':
    main()

Solution (Python):
x,y,z,k=map(int,input().split())
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
c=[int(i) for i in input().split()]


ab=[]

for i in a:
    for j in b:
        ab.append(i+j)
ab.sort()
ab.reverse()
ans=[]
for i in range(min(k,len(ab))):
    for j in c:
        ans.append(ab[i]+j)
ans.sort()
ans.reverse()

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

Solution (Python):
x,y,z,k=[int(x) for x in input().split()]
a=[int(x) for x in input().split()]
b=[int(x) for x in input().split()]
c=[int(x) for x in input().split()]
ab=[]
for i in range(x):
    for j in range(y):
        ab.append(a[i]+b[j])
ab=sorted(ab,reverse=True)[:3001]
abc=[]
for i in ab:
    for j in c:
        abc.append(i+j)
abc=sorted(abc,reverse=True)
for i in range(k):
    print(abc[i])

Solution (Python):
from heapq import heappush, heappop
X, Y, Z, K = map(int, input().split())
*A, = map(int, input().split())
*B, = map(int, input().split())
*C, = map(int, input().split())

S = []
for a in A:
    for b in B:
        S.append(a+b)
S.sort()
que = []
L = X*Y
for c in C:
    heappush(que, (-S[-1]-c, L-1, c))
T = C

ans = []
for _ in range(K):
    v, i, c = heappop(que)
    ans.append(-v)
    if i > 0:
        heappush(que, (-S[i-1]-c, i-1, c))
print(*ans[:K], sep='\n')

Solution (Python):
x,y,z,k = map(int,input().split())

info = [list(map(int,input().split())) for i in range(3)]
info[0]=sorted(info[0],reverse=True)
info[1]=sorted(info[1],reverse=True)
info[2]=sorted(info[2],reverse=True)
li = []
ans = []
li_append = li.append 
ans_append = ans.append

for i in info[0]:
  for j in info[1]:
    li_append(i+j)
li = sorted(li,reverse=True)

for i in li[:3000]:
  for j in info[2]:
    ans_append(i+j)
ans = sorted(ans,reverse = True)

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

Solution (Python):
import itertools
from bisect import bisect_left

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 = list(map(lambda a: a[0]+a[1], itertools.product(A, B)))
AB.sort()

C.sort()
C.reverse()
c0 = C[0]
ans = [c0 + ab for ab in AB][-K:]
AB.reverse()
for c in C[1:]:
  for ab in AB:
    abc = ab + c
    i = bisect_left(ans, abc)
    if i > len(ans) - K:
      ans = (ans[:i] + [abc] + ans[i:])[-K:]
    else:
      break
ans.reverse()
for abc in ans:
  print(abc)

Solution (Python):
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()
b.sort()
c.sort()

res1=[]
for i in range(x):
    for j in range(y):
        res1.append(a[i]+b[j])
res1.sort()
res2=[]
for i in range(min(K,x*y)):
    for k in range(z):
        res2.append(res1[-i-1]+c[k])
res2.sort()
for i in range(K):
    print(res2[-1-i])

Solution (Python):
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from heapq import heappush, heappop
from collections import defaultdict

x,y,z,k = li()
a = list(li())
b = list(li())
c = list(li())

a.sort()
b.sort()
c.sort()

acur = x-1
bcur = y-1
ccur = z-1

deli = []
que = [(-a[-1]-b[-1]-c[-1], x-1, y-1, z-1)]
searched = defaultdict(bool)

while len(deli) < k:
    good, acur, bcur, ccur = heappop(que)
    deli.append(-good)
    
    if acur > 0 and not searched[(acur-1, bcur, ccur)]:
        heappush(que, (-a[acur-1]-b[bcur]-c[ccur], acur-1, bcur, ccur))
        searched[(acur-1, bcur, ccur)] = True
    
    if bcur > 0 and not searched[(acur, bcur-1, ccur)]:
        heappush(que, (-a[acur]-b[bcur-1]-c[ccur], acur, bcur-1, ccur))
        searched[(acur, bcur-1, ccur)] = True
    
    if ccur > 0 and not searched[(acur, bcur, ccur-1)]:
        heappush(que, (-a[acur]-b[bcur]-c[ccur-1], acur, bcur, ccur-1))
        searched[(acur, bcur, ccur-1)] = True
        
for di in deli:
    print(di)