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):
import bisect

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

x = sorted(list(map(int, input().split())), reverse=True)
y = sorted(list(map(int, input().split())), reverse=True)
z = sorted(list(map(int, input().split())), reverse=True)

x_i = 0
y_i = 0
z_i = 0

def cand_index(x_i, y_i, z_i):
    cs = [(x_i+1, y_i, z_i)] if x_i+1 < X else []
    cs += [(x_i, y_i+1, z_i)] if y_i+1 < Y else []
    cs += [(x_i, y_i, z_i+1)] if z_i+1 < Z else []
    return set(cs)

num_xyz = [[x[0]+ y[0]+ z[0], (0, 0, 0)]]
used = set()
ans = []
num = 0
for _ in range(K):
    num, xyz = num_xyz.pop(0)
    ans.append(num)

    new_cand = cand_index(*xyz)
    cand = new_cand - used
    used |= new_cand

    num_xyz += [[x[xyz[0]] + y[xyz[1]] + z[xyz[2]], xyz] for xyz in cand]
    num_xyz = sorted(num_xyz, key=lambda x: x[0], reverse=True)

for a in ans:
    print(a)

Solution (Python):
def ii2ss(n):
    ss = []
    for i in range(n):
        ss.append(input())
    return ss

def sp2nn(sp, sep=' '):
    return [int(s) for s in sp.split(sep)]

def ss2nn(ss):
    return [int(s) for s in list(ss)]

def tk(i, j, k):
    return '%d %d %d' % (i, j, k)

def tkr(key):
    return sp2nn(key)

def main(ss):
    X, Y, Z, K = sp2nn(ss[0])
    aa = sp2nn(ss[1])
    bb = sp2nn(ss[2])
    cc = sp2nn(ss[3])
    aa.sort()
    aa.reverse()
    bb.sort()
    bb.reverse()
    cc.sort()
    cc.reverse()
    
    d = {}
    st = set()
    key = tk(0, 0, 0)
    st.add(key)
    d[key] = aa[0] + bb[0] + cc[0]
    for _ in range(K):
        vmax = -1
        vk = ''
        for k, v in d.items():
            if vmax < v:
                vmax = v
                vk = k
        print(vmax)
        d.pop(vk)
        st.add(vk)
        i, j, k = tkr(vk)
        if i + 1 < len(aa):
            key = tk(i+1, j, k)
            if key not in st:
                d[key] = aa[i+1] + bb[j] + cc[k]
        if j + 1 < len(bb):
            key = tk(i, j+1, k)
            if key not in st:
                d[key] = aa[i] + bb[j+1] + cc[k]
        if k + 1 < len(cc):
            key = tk(i, j, k+1)
            if key not in st:
                d[key] = aa[i] + bb[j] + cc[k+1]
        
main(ii2ss(4))

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()))
ab=[]
for i in range(x):
    for j in range(y):
        ab+=[a[i]+b[j]]
ab.sort(key=lambda x: -x)
c.sort(key=lambda x: -x)
ans=[]
ct=[0]
ansc=[ab[0]+c[0]]
while (len(ans)<k):
    if(ct[-1]!=0 and len(ct)<z):
        ansc+=[ab[0]+c[len(ct)]]
        ct+=[0]
    ans+=[max(ansc)]
    tmp=ansc.index(max(ansc))
    if(ct[tmp]==len(ab)-1):
        ansc[tmp]=0
    else:
        ct[tmp]+=1
        ansc[tmp]=ab[ct[tmp]]+c[tmp]
for i in ans:
    print(i)

Solution (Python):
import queue
import heapq

class point:
    def __init__(self):
        self.num = 0
        self.line = [0 for _ in range(3)]

    def __lt__(self, other):
        return self.num > other.num


ABC = list(map(int, input().split()))
K = ABC[-1]
ABC.pop()
ABCL = [list(map(int, input().split())) for _ in range(3)]
for i in range(3):
    ABCL[i] = sorted(ABCL[i])
    ABCL[i] = list(reversed(ABCL[i]))
s = set()
p = point()
p.num = sum([ABCL[i][0] for i in range(3)])
s.add(tuple(p.line))
que = []
heapq.heappush(que, p)
for _ in range(K):
    c = heapq.heappop(que)
    print(c.num)
    for i in range(3):
        d = point()
        d.num = c.num
        for j in range(3):
            d.line[j] = c.line[j]
        if d.line[i] + 1 == ABC[i]:
            continue
        d.num -= ABCL[i][d.line[i]]
        d.line[i] += 1
        d.num += ABCL[i][d.line[i]]
        if tuple(d.line) in s:
            continue
        s.add(tuple(d.line))
        heapq.heappush(que, d)

Solution (Python):
from collections import defaultdict
d = defaultdict(list)
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)

AN = min(K+1,len(A))
BN = min(K+1,len(B))
CN = min(K+1,len(C))
AD =  [A[i]-A[i+1] for i in range(AN-1)]
BD =  [B[i]-B[i+1] for i in range(BN-1)]
CD =  [C[i]-C[i+1] for i in range(CN-1)]

d[0].append([0,0,0])

m = A[0]+B[0]+C[0]
cnt = 0
off = []
while(True):
	if not d:
		exit()
	r = min(d)
	for ind in d[r][:]:
		off.append(ind)
		print(m-r)
		cnt = cnt + 1
		if cnt >= K:
			exit()
		ia,ib,ic = ind
		if ia < AN-1:
			add = [ia+1,ib,ic]
			if not add in off:
				off.append(add)
				d[r+AD[ia]].append(add)
		if ib < BN-1:
			add = [ia,ib+1,ic]
			if not add in off:
				off.append(add)
				d[r+BD[ib]].append(add)
		if ic < CN-1:
			add = [ia,ib,ic+1]
			if not add in off:
				off.append(add)
				d[r+CD[ic]].append(add)
		d[r].remove(ind)
	if not d[r]:
		del d[r]

Solution (Python):
from collections import defaultdict
inpl = lambda: list(map(int,input().split()))

X, Y, Z, K = inpl()
A = [ sorted(inpl(), key=lambda x: -x) for _ in range(3) ]
N = [X, Y, Z]

mem = defaultdict(int)
ans = sum([A[i][0] for i in range(3)])
mem[(0,0,0)] = 1
cand = [(ans,0,0,0)]

for i in range(K):
    cand.sort()
    c = cand[-1]
    print(c[0])
    n = [c[1],c[2],c[3]]
    cand.pop(-1)
    
    for p in range(3):
        if n[p] < N[p]-1:
            n[p] += 1
            if mem[(n[0],n[1],n[2])] == 0:
                mem[(n[0],n[1],n[2])] = 1
                cand.append((sum([A[j][n[j]] for j in range(3)]),n[0],n[1],n[2]))
            n[p] -= 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()))

A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)

apb =  []

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

apb = apb[:K]
ans = []

for k in apb:
    for c in (C):
        ans.append(k+c)
ans.sort(reverse=True)

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

Solution (Python):

import itertools
import sys
import math
from functools import lru_cache





from queue import Queue
from operator import mul
from functools import reduce
from queue import Queue
from operator import mul
from functools import reduce
from functools import lru_cache

input = sys.stdin.readline


x, y, z, kk = list(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)


ll = []
count = 0
for i in range(len(a)):
    for j in range(len(b)):
        if i * j > kk:

            break
        for k in range(len(c)):
            if i * j * k > kk:
                break
            ll.append(a[i] + b[j] + c[k])
ll.sort(reverse=True)

for i in range(kk):
    print(ll[i])

Solution (Python):
import numpy as np


x, y, z, k = map(int, input().split())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))
Cs = list(map(int, input().split()))

As = sorted(As, reverse=True)
Bs = sorted(Bs, reverse=True)
Cs = sorted(Cs, reverse=True)

idx_1, idx_2, idx_3 = 0, 0, 0
INF = 10 ** 11
answers = list()

candidates = [(idx_1, idx_2, idx_3)]
end_cands = set()
values = [As[idx_1] + Bs[idx_2] + Cs[idx_3]]
for i in range(k):
    while True:
        ans_idx = np.argmax(values)
        cand = candidates.pop(ans_idx)
        ans = values.pop(ans_idx)
        if cand not in end_cands:
            break
    idx_1, idx_2, idx_3 = cand
    answers.append(ans)
    end_cands.add(cand)
    

    if idx_1 + 1 != x:
        candidates.append((idx_1 + 1, idx_2, idx_3))
        values.append(As[idx_1 + 1] + Bs[idx_2] + Cs[idx_3])
    if idx_2 + 1 != y:
        candidates.append((idx_1, idx_2 + 1, idx_3))
        values.append(As[idx_1] + Bs[idx_2 + 1] + Cs[idx_3])
    if idx_3 + 1 != z:
        candidates.append((idx_1, idx_2, idx_3 + 1))
        values.append(As[idx_1] + Bs[idx_2] + Cs[idx_3 + 1])

for ans in answers:
    print(ans)

Solution (Python):
from heapq import heappush, heappop

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()]
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
h = []

maxv = A[0] + B[0] + C[0]


def inv(v):
    return maxv - v


pushed = [[[] for _ in range(Y)] for _ in range(X)]
heappush(h, (0, 0, 0, 0))
for _ in range(K):
    invv, i, j, k = heappop(h)
    print(inv(invv))
    if i + 1 < X and k not in pushed[i + 1][j]:
        heappush(h, (inv(A[i + 1] + B[j] + C[k]), i + 1, j, k))
        pushed[i + 1][j].append(k)
    if j + 1 < Y and k not in pushed[i][j + 1]:
        heappush(h, (inv(A[i] + B[j + 1] + C[k]), i, j + 1, k))
        pushed[i][j + 1].append(k)
    if k + 1 < Z and k + 1 not in pushed[i][j]:
        heappush(h, (inv(A[i] + B[j] + C[k + 1]), i, j, k + 1))
        pushed[i][j].append(k + 1)

Solution (Python):
x,y,z,k = map(int,input().split())
lisa = list(map(int,input().split()))
lisb = list(map(int,input().split()))
lisc = list(map(int,input().split()))
lisa.sort(reverse=True)
lisb.sort(reverse=True)
lisc.sort(reverse=True)
an = []
ans = []
for num in lisb:
    for nu in lisa:
        an.append(num+nu)
an.sort(reverse=True)
an = an[:min(3001,x*y*z+1)]
for num in lisc:
    for nu in an:
        ans.append(num+nu)
ans.sort(reverse=True)
for i in range(k):
    print(ans[i])

Solution (Python):



from collections import deque, defaultdict
import bisect

X, Y, Z, K = map(int, input().rstrip().split(' '))
A = sorted(list(map(int, input().rstrip().split(' '))))[::-1]
B = sorted(list(map(int, input().rstrip().split(' '))))[::-1]
C = sorted(list(map(int, input().rstrip().split(' '))))[::-1]

ai = 0
bi = 0
ci = 0


diff = [1, 0, -1]
memo = set()
memo.add('000000000000')
    
d = defaultdict(lambda: [])
current_total = A[ai] + B[bi] + C[ci]
totals = [current_total]
d[current_total].append([ai, bi, ci])
current_total_index = 0
count = 0
while True:
    current_total = totals[-(current_total_index+1)]

    for candidate in d[current_total]:
        count += 1
        ai, bi, ci = candidate
        print(current_total)
        if count >= K:
            break
        for i in diff:
            for j in diff:
                for k in diff:
                    if (ai + i) < 0 or (ai + i) >= len(A) or (bi + j) < 0 or (bi + j) >= len(B) or (ci + k) < 0 or (ci + k) >= len(C):
                        continue
                    
                    before_len_memo = len(memo)
                    memo.add('{:04d}{:04d}{:04d}'.format(ai + i, bi + j, ci + k))
                    if before_len_memo != len(memo):
                        total = A[ai+i] + B[bi+j] + C[ci+k]
                        
                        if len(d[total]) == 0:
                            bisect.insort_right(totals, total)
                        
                        d[total].append([ai+i, bi+j, ci+k])
                    
        
    if count >= K:
        break
        
    current_total_index += 1

Solution (Python):
import heapq

x, y, z, k = map(int, input().split())
ali = list(reversed(sorted(map(int, input().split()))))
bli = list(reversed(sorted(map(int, input().split()))))
cli = list(reversed(sorted(map(int, input().split()))))

done = {}
count = 0

heap = []


def main(a, b, c):
    global count
    if '{}'.format((a, b, c)) in done:
        return
    done['{}'.format((a, b, c))] = True
    count += 1
    print(ali[a] + bli[b] + cli[c])
    if a + 1 < x:
        heapq.heappush(heap, (-(ali[a + 1] + bli[b] + cli[c]), a + 1, b, c))
    if b + 1 < y:
        heapq.heappush(heap, (-(ali[a] + bli[b + 1] + cli[c]), a, b + 1, c))
    if c + 1 < z:
        heapq.heappush(heap, (-(ali[a] + bli[b] + cli[c + 1]), a, b, c + 1))


main(0, 0, 0)
while count < k:
    s, a, b, c = heapq.heappop(heap)
    main(a, b, c)

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

Solution (Python):
x,y,z,k = map(int,input().split())
lisa = list(map(int,input().split()))
lisb = list(map(int,input().split()))
lisc = list(map(int,input().split()))
lisa.sort(reverse=True)
lisb.sort(reverse=True)
lisc.sort(reverse=True)
an = []
ans = []
for num in lisb:
    for nu in lisa:
        an.append(num+nu)
an.sort(reverse=True)
an = an[:min(3001,x*y*z+1)]
for num in lisc:
    for nu in an:
        ans.append(num+nu)
ans.sort(reverse=True)
for i in range(k):
    print(ans[i])

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 = []
    heapq.heappush(cand, (-s(0, 0, 0), (0, 0, 0)))
    for _ in range(K):
        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):
x,y,z,k = map(int,input().split())

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

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):
read = input
def read_numbers():
    a = read().split(' ')
    a = list(map(int, a))
    return a
[x,y,z,K] = read_numbers()
memo = [[set() for i in range(y)]for i in range(x)]
X = read_numbers()
Y = read_numbers()
Z = read_numbers()
X.sort()
X.reverse()
Y.sort()
Y.reverse()
Z.sort()
Z.reverse()
import queue
def cal(px, py,pz):
    return X[px]+Y[py]+Z[pz]
memo[0][0].add(0)
cnt = 0
pq = queue.PriorityQueue()

pq.put((-cal(0,0,0) ,0,0,0))
while(cnt < K):

    cost , px, py, pz = pq.get(timeout=1)

    for i in range(px-1, px + 2):
        for j in range(py-1, py + 2):
            for k in range(pz-1, pz + 2):
                if (i >= 0 and i < x and 
                    j >= 0 and j < y and 
                    k >=0 and k < z and
                    k not in memo[i][j]
                   ):
                    memo[i][j].add(k)
                    pq.put((-cal(i,j,k),i,j,k))
    print(-cost)
    cnt = cnt + 1

Solution (Python):
import numpy as np
import itertools
x,y,z,k = [int(_) for _ in input().split(" ")]
A = np.array([int(_) for _ in input().split(" ")])
B = np.array([int(_) for _ in input().split(" ")])                                                  
C = np.sort([int(_) for _ in input().split(" ")])

AB = A.reshape(1,x) + B.reshape(y,1)
sorted_ab  = np.sort(AB.flatten())[::-1][:k]
abc = np.expand_dims(sorted_ab,0) + C.reshape(z,1)
sorted_abc = np.sort(abc.flatten())[::-1]
for i in range(k):
    print(sorted_abc[i])

Solution (Python):

import sys
import heapq
R=lambda:map(int,sys.stdin.readline().split())
xa,xb,xc,k=R()
a=sorted(R())
b=sorted(R())
c=sorted(R())
h=set()
q=[[-(a[-1]+b[-1]+c[-1]),xa-1,xb-1,xc-1]]
for _ in range(k):
	x,ya,yb,yc=heapq.heappop(q)
	print(-x)
	if ya>0 and (ya-1,yb,yc) not in h:
		h.add((ya-1,yb,yc))
		heapq.heappush(q,[x+a[ya]-a[ya-1],ya-1,yb,yc])
	if yb>0 and (ya,yb-1,yc) not in h:
		h.add((ya,yb-1,yc))
		heapq.heappush(q,[x+b[yb]-b[yb-1],ya,yb-1,yc])
	if yc>0 and (ya,yb,yc-1) not in h:
		h.add((ya,yb,yc-1))
		heapq.heappush(q,[x+c[yc]-c[yc-1],ya,yb,yc-1])

Solution (Python):
import numpy as np
import math

xyzk=input().split()
X=int(xyzk[0])
Y=int(xyzk[1])
Z=int(xyzk[2])
K=int(xyzk[3])
A = list(map(int,input().split()))
B = list(map(int,input().split()))
C = list(map(int,input().split()))
xy_size = min(3000,X*Y)
xy = np.zeros((X,Y))
for i in range(X):
    xy[i,:] += A[i]
for i in range(Y):
    xy[:,i] += B[i]
xy = np.sort(xy.reshape(-1))[::-1][:xy_size]


xyz = np.zeros((xy_size,Z))
for i in range(xy_size):
    xyz[i,:] += xy[i]
for i in range(Z):
    xyz[:,i] += C[i]

xyz = np.sort(xyz.reshape(-1))[::-1][:K]

for num in xyz:
    print(int(num))

Solution (Python):
INF = -10**11
x, y, z, k = [int(item) for item in input().split()]
a = sorted([int(item) for item in input().split()], reverse=True) + [INF]
b = sorted([int(item) for item in input().split()], reverse=True) + [INF]
c = sorted([int(item) for item in input().split()], reverse=True) + [INF]

num = x + y + z
ac, bc, cc = 0, 0, 0
ad = a[0] - a[1]
bd = b[0] - b[1]
cd = c[0] - c[1]
kadd = min(12000, x*y*z)
while (ac+1) * (bc+1) * (cc+1) < kadd:
    if ad <= bd and ad <= cd:
        ac += 1
        ad = a[ac] - a[ac+1]
    elif bd <= ad and bd <= cd:
        bc += 1
        bd = b[bc] - b[bc+1]
    elif cd <= ad and cd <= bd:
        cc += 1
        cd = c[cc] - c[cc+1]

for i in range(30):
    if ac+1 < x:
        ac += 1
    if bc+1 < y:
        bc += 1
    if cc+1 < z:
        cc += 1

vals = []
for ai in a[:ac+1]:
    for bi in b[:bc+1]:
        for ci in c[:cc+1]:
            vals.append(ai+bi+ci)
vals.sort(reverse=True)
for i in range(k):
    print(vals[i])

Solution (Python):

import sys
import itertools
import collections
import functools
import math
from queue import Queue

INF = float("inf")
import heapq


def solve(X: int, Y: int, Z: int, K: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    XYZ = [X, Y, Z]
    A.sort(reverse=True)
    B.sort(reverse=True)
    C.sort(reverse=True)
    ABC = [A, B, C]

    base = A[0]+B[0]+C[0]
    cand = [[0, 0, 0, 0]]
    heapq.heapify(cand)
    
    for i in range(K):
        a = heapq.heappop(cand)
        for j in range(1, 4):
            if a[j]+1 < XYZ[j-1]:
                b = [a[0]+ABC[j-1][a[j]]-ABC[j-1][a[j]+1],
                     a[1]+int(j == 1),
                     a[2]+int(j == 2),
                     a[3]+int(j == 3)]
                if b not in cand:
                    heapq.heappush(cand, b)
        
        print(base-a[0])
    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):
import sys
from itertools import product

_, _, _, k = [int(v) for v in sys.stdin.readline().split(" ")]
xs = [int(v) for v in sys.stdin.readline().split(" ")]
ys = [int(v) for v in sys.stdin.readline().split(" ")]
zs = [int(v) for v in sys.stdin.readline().split(" ")]


xys = sorted([x + y for x, y in product(xs, ys)], reverse=True)
zs = sorted(zs, reverse=True)
ret = [a + b for a, b in zip([zs[0]] * k, xys)]
for z in zs[1:]:
    rr = ret[:]
    r2 = [a + b for a, b in zip([z] * k, xys)]
    ret = sorted(ret + r2, reverse=True)[:k]
    if ret == rr:
        break
print('\n'.join([str(v) for v in ret]))

Solution (Python):
from queue import PriorityQueue
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)
A.append(-float('inf'))
B.sort(reverse=True)
B.append(-float('inf'))
C.sort(reverse=True)
C.append(-float('inf'))

pq = PriorityQueue()
pq.put((-(A[0]+B[0]+C[0]),0,0,0))
count = 0
queued = set([(0,0,0)])
while True:
  d,i,j,k = pq.get()
  
  print(-d)
  count += 1
  if count >= K:
    break
  for l in [i,i+1]:
    for m in [j,j+1]:
      for n in [k,k+1]:
        if (l,m,n) in queued:
          continue
        else:
          pq.put((-(A[l]+B[m]+C[n]),l,m,n))
          queued.add((l,m,n))

Solution (Python):
import heapq
X,Y,Z,K=[int(i) for i in 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 a in A:
    for b in B:
        AB.append(a+b)

AB=heapq.nlargest(K,AB)
ABC=[]
for ab in AB:
    for c in C:
        ABC.append(ab+c)

for cake in heapq.nlargest(K,ABC):
    print(cake)

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()))

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)

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

ans = []
for _ in range(K):
    ans.append(-heapq.heappop(hq))
    heapq.heappop(hq)
    heapq.heappop(hq)

print(*ans, sep='\n')

Solution (Python):
X, Y, Z, K = map(int, input().split())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))
Cs = list(map(int, input().split()))

sum12s = []
for A in As:
    for B in Bs:
        sum12s.append(A+B)
sum12s.sort(reverse=True)
sum12s = sum12s[:K] + [-1]

anss = [] + [-1]
for C in Cs:
    ans2s = []
    iAns = iSum12 = 0
    for _ in range(min(K, len(anss)+len(sum12s)-2)):
        if anss[iAns] >= C+sum12s[iSum12]:
            ans2s.append(anss[iAns])
            iAns += 1
        else:
            ans2s.append(C+sum12s[iSum12])
            iSum12 += 1
    anss = ans2s + [-1]

print('\n'.join(map(str, anss[:-1])))

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

A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
m = A[0]+B[0]+C[0]

counted=set([])
in_heap=set([])

hp = []
heapq.heapify(hp)
heapq.heappush(hp, (0, (0,0,0)))



for _ in range(K):
  x = heapq.heappop(hp)
  print(m-x[0])
  counted.add(x[1])
  a,b,c = x[1]
  if (a+1, b,c) not in counted and (a+1, b,c) not in in_heap and a<len(A)-1:
    heapq.heappush(hp, (m-A[a+1]-B[b]-C[c], (a+1,b,c)))
    in_heap.add((a+1, b, c))
  if (a, b+1,c) not in counted and (a, b+1,c) not in in_heap and b<len(B)-1:
    heapq.heappush(hp, (m-A[a]-B[b+1]-C[c], (a,b+1,c)))
    in_heap.add((a,b+1,c))
  if (a, b,c+1) not in counted and (a, b,c+1) not in in_heap and c<len(C)-1:
    heapq.heappush(hp, (m-A[a]-B[b]-C[c+1], (a,b,c+1)))
    in_heap.add((a,b,c+1))

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()))

A.sort(reverse = True)
B.sort(reverse = True)
C.sort(reverse = True)
A += [-1e10]
B += [-1e10]
C += [-1e10]

memo = [A[i] + B[0] + C[0] for i in range(X + 1)]
L = [[0 for i in range(Y + 1)] for j in range(X + 1)]

for i in range(K):
  ma = 0
  for j in range(X):
    if memo[ma] < memo[j]:
      ma = j
  print(memo[ma])
  mb = 0
  mn = 0
  for j in range(Y):
    x = B[j] + C[L[ma][j]]
    if mb < x:
      mb = x
      mn = j
  L[ma][mn] += 1
  n = 0
  for j in range(Y):
    n = max(n, B[j] + C[L[ma][j]])
  memo[ma] = A[ma] + n

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

bc = []

for b in B:
    for c in C:
        bc.append(b+c)

bc.sort(reverse=True)
t = min(len(bc), 3333)
bc = bc[:t]
cnt = 0
cand = []

for a in A:
    cnt = 0
    for i in bc:
        cnt += 1
        cand += [a + i]
        if cnt == 3000:
            break

cand.sort(reverse=True)
cnt = 0
for i in cand:
    print(i)
    cnt += 1
    if cnt == k:
        break

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()))

a = sorted(a)
b = sorted(b)
c = sorted(c)

n = []
heapq.heapify(n)
heapq.heappush(n, (-(a[-1]+b[-1]+c[-1]), 1, 1, 1))
for _ in range(K):
    (m, i, j, k) = heapq.heappop(n)
    print(-m)
    if i + 1 <= x:
        s = (-(a[-i-1]+b[-j]+c[-k]), i+1, j, k)
        if s not in n:
            heapq.heappush(n, s)
    if j + 1 <= y:
        s = (-(a[-i]+b[-j-1]+c[-k]), i, j+1, k)
        if s not in n:
            heapq.heappush(n, s)
    if k + 1 <= z:
        s = (-(a[-i]+b[-j]+c[-k-1]), i, j, k+1)
        if s not in n:
            heapq.heappush(n, s)

Solution (Python):
x, y, z, k = map(int, input().split())
alist = list(sorted(map(int, input().split()), key=lambda x: -x)) + [-pow(10, 10)]
blist = list(sorted(map(int, input().split()), key=lambda x: -x)) + [-pow(10, 10)]
clist = list(sorted(map(int, input().split()), key=lambda x: -x)) + [-pow(10, 10)]

setk = set([(0, 0, 0, alist[0] + blist[0] + clist[0])])
outk = set()

for _ in range(k):
  tmpk = None
  tmpi = 0
  for i, _k in enumerate(setk):
    if tmpk is None:
      tmpk = _k
      tmpi = i
    elif tmpk[3] < _k[3]:
      tmpk = _k
      tmpi = i
  print(tmpk[3])
  outk.add(tmpk)
  setk.discard(tmpk)
  if (tmpk[0] + 1, tmpk[1], tmpk[2], tmpk[3] - alist[tmpk[0]] + alist[tmpk[0] + 1]) not in outk:
    setk.add((tmpk[0] + 1, tmpk[1], tmpk[2], tmpk[3] - alist[tmpk[0]] + alist[tmpk[0] + 1]))
  if (tmpk[0], tmpk[1] + 1, tmpk[2], tmpk[3] - blist[tmpk[1]] + blist[tmpk[1] + 1]) not in outk:
    setk.add((tmpk[0], tmpk[1] + 1, tmpk[2], tmpk[3] - blist[tmpk[1]] + blist[tmpk[1] + 1]))
  if (tmpk[0], tmpk[1], tmpk[2] + 1, tmpk[3] - clist[tmpk[2]] + clist[tmpk[2] + 1]) not in outk:
    setk.add((tmpk[0], tmpk[1], tmpk[2] + 1, tmpk[3] - clist[tmpk[2]] + clist[tmpk[2] + 1]))

Solution (Python):
import heapq

x, y, z, k = map(int, raw_input().split())
a = map(int, raw_input().split())
b = map(int, raw_input().split())
c = map(int, raw_input().split())

def diff(l):
    m = max(l)
    return sorted(m - v for v in l)[1:]

s = sum(map(max, [a, b, c]))
sa, sb, sc = map(diff, [a, b, c])
da, db, dc = [0], [0], [0]
q = [0]
while k > 0:
    while True:
        if len(sa) > 0 and (len(q) == 0 or q[0] > sa[0]):
            for v in [sa[0] + bb + cc for bb in db for cc in dc]:
                heapq.heappush(q, v)
            da.append(sa[0])
            sa = sa[1:]
        elif len(sb) > 0 and (len(q) == 0 or q[0] > sb[0]):
            for v in [sb[0] + aa + cc for aa in da for cc in dc]:
                heapq.heappush(q, v)
            db.append(sb[0])
            sb = sb[1:]
        elif len(sc) > 0 and (len(q) == 0 or q[0] > sc[0]):
            for v in [sc[0] + aa + bb for aa in da for bb in db]:
                heapq.heappush(q, v)
            dc.append(sc[0])
            sc = sc[1:]
        else:
            break
    v = heapq.heappop(q)
    print s - v
    k -= 1