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:
def main():
    import heapq

    x, y, z, k, *abc = map(int, open(0).read().split())
    a = abc[:x]
    b = abc[x:x + y]
    c = abc[x + y:]
    d = []

    a.sort(reverse=True)
    b.sort(reverse=True)
    c.sort(reverse=True)

    h = [(-(a[0] + b[0] + c[0]), 0, 0, 0)]
    heapq.heapify(h)
    ans = []
    for _ in range(k):
        p, i, j, k = heapq.heappop(h)
        ans.append(-p)
        for p, q, r in [(1, 0, 0), (0, 1, 0), (0, 0, 1)]:
            if i + p < x and j + q < y and k + r < z:
                if (i + p, j + q, k + r) not in d:
                    d.append((i + p, j + q, k + r))
                    v = - (a[i + p] + b[j + q] + c[k + r])
                    heapq.heappush(h, (v, i + p, j + q, k + r))

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    import heapq
    from collections import defaultdict

    x, y, z, k, *abc = map(int, open(0).read().split())
    a = abc[:x]
    b = abc[x:x + y]
    c = abc[x + y:]
    d = defaultdict(list)

    a.sort(reverse=True)
    b.sort(reverse=True)
    c.sort(reverse=True)

    h = [(-(a[0] + b[0] + c[0]), 0, 0, 0)]
    heapq.heapify(h)
    ans = []
    for _ in range(k):
        p, i, j, k = heapq.heappop(h)
        ans.append(-p)
        for p, q, r in [(1, 0, 0), (0, 1, 0), (0, 0, 1)]:
            if i + p < x and j + q < y and k + r < z:
                if (j + q, k + r) not in d[i + p]:
                    d[i + p].append((j + q, k + r))
                    v = - (a[i + p] + b[j + q] + c[k + r])
                    heapq.heappush(h, (v, i + p, j + q, k + r))

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

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

# ab = []
# for i in a:
#     for j in b:
#         ab.append(i+j)
# ab.sort(reverse=True)

# ab = ab[:k]

# abc = []
# for i in ab:
#     for j in c:
#         abc.append(i+j)
# abc.sort(reverse=True)

# for i in range(k):
#     print(abc[i])

a.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)

a_max = min(k, len(a))
b_max = min(k, len(b))
c_max = min(k, len(c))

abc = []
for i in range(1, k+1):
    if i > len(a):
        break
    for j in range(1, k//i+1):
        if j > len(b):
            break
        for l in range(1, k//(i*j)+1):
            if l > len(c):
                break
            # print(i, j, l)
            abc.append(a[i-1]+b[j-1]+c[l-1])

# print(abc)
# print(k)
abc.sort(reverse=True)
for i in range(k):
    print(abc[i])

Submission status: Accepted

Solution code:
import sys
#import numpy as np
import math
#from fractions import Fraction
#import itertools
from collections import deque
#import heapq
from fractions  import gcd

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=[0]*(x*y)
c.sort(reverse=True)
for i in range(x):
    for j in range(y):
        ab[y*i+j]=a[i]+b[j]
ab.sort(reverse=True)
d=ab[:k]
ans=[0]*(k*z)
for i in range(len(d)):
    for j in range(z):
        ans[z*i+j]=d[i]+c[j]
ans.sort(reverse=True)
for i in range(k):
    print(ans[i])

Submission status: Accepted

Solution code:
import numpy as np
from collections import deque
from collections import defaultdict
import heapq
import collections
import itertools
import bisect

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 = sorted(A, reverse=True)
B = sorted(B, reverse=True)
C = sorted(C, reverse=True)
i, j, k = 0, 0, 0
heap = [(-A[i] - B[j] - C[k], i, j, k)]
heapq.heapify(heap)
used_set = set([(i, j, k)])
for _ in range(K):
    oisi, i, j, k = heapq.heappop(heap)
    print(-oisi)
    if (i+1, j, k) in used_set:
        pass
    elif(i+1 < len(A)):
        used_set.add((i+1, j, k))
        heapq.heappush(heap, (-A[i+1]-B[j]-C[k], i+1, j, k))
    if (i, j+1, k) in used_set:
        pass
    elif(j+1 < len(B)):
        used_set.add((i, j+1, k))
        heapq.heappush(heap, (-A[i] - B[j+1] - C[k], i, j+1, k))
    if (i, j, k+1) in used_set:
        pass
    elif(k+1 < len(C)):
        used_set.add((i, j, k+1))
        heapq.heappush(heap, (-A[i]-B[j]-C[k+1], i, j, k+1))

Submission status: Accepted

Solution code:
from heapq import *
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,reverse = True)
B = sorted(B,reverse = True)
C = sorted(C,reverse = True)

cake = []
heapify(cake)
for x in range(X):
  for y in range(min(Y,K//(x+1)+1)):
    for k in range(min(Z,K//((x+1)*(y+1))+1)):
      heappush(cake,-(A[x]+B[y]+C[k]))
for _ in range(K):
  print(abs(heappop(cake)))

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()))
ab = []
for i in range(x):
    for j in range(y):
        ab.append(a[i] + b[j])
ab.sort(reverse=True)
ab = ab[:k]
rec = []
for i in range(min(x*y, k)):
    for j in range(z):
        rec.append(ab[i] + c[j])

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

Submission status: Accepted

Solution code:
import heapq
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()]
a.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)
al = []

hq = []
heapq.heappush(hq,(-(a[0]+b[0]+c[0]),0,0,0))
for i in range(k):
    hqi,ai,bi,ci = heapq.heappop(hq)
    print(-hqi)
    if ai+1 < x and not (ai+1,bi,ci) in al:
        heapq.heappush(hq,(-(a[ai+1]+b[bi]+c[ci]),ai+1,bi,ci))
        al.append((ai+1,bi,ci))
    if bi+1 < y and not (ai,bi+1,ci) in al:
        heapq.heappush(hq,(-(a[ai]+b[bi+1]+c[ci]),ai,bi+1,ci))
        al.append((ai,bi+1,ci))
    if ci+1 < z and not (ai,bi,ci+1) in al:
        heapq.heappush(hq,(-(a[ai]+b[bi]+c[ci+1]),ai,bi,ci+1))
        al.append((ai,bi,ci+1))

Submission status: Accepted

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

ab=[i+j for j in b for i in a]
ab.sort(reverse=True)
abc=[i+j for j in c[:k] for i in ab[:k]]
abc.sort(reverse=True)

print(*abc[:k],sep='\n')

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
from collections import defaultdict


def main():
    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)
    que = [(- A[0] - B[0] - C[0], 0, 0, 0)]  # multiply -1 to change min to max
    already_inserted = defaultdict(int)
    answer = list()
    for _ in range(K):
        q, i, j, k = heappop(que)
        answer.append(-q)
        if i + 1 < X:
            item_a = (- A[i + 1] - B[j] - C[k], i + 1, j, k)
            if already_inserted[item_a] == 0:
                heappush(que, item_a)
                already_inserted[item_a] = 1
        if j + 1 < Y:
            item_b = (- A[i] - B[j + 1] - C[k], i, j + 1, k)
            if already_inserted[item_b] == 0:
                heappush(que, item_b)
                already_inserted[item_b] = 1
        if k + 1 < Z:
            item_c = (- A[i] - B[j] - C[k + 1], i, j, k + 1)
            if already_inserted[item_c] == 0:
                heappush(que, item_c)
                already_inserted[item_c] = 1
    for ans in answer:
        print(ans)


if __name__ == '__main__':
    main()

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

ab=[]

for aa in a:
    for bb in b:
        ab.append(aa+bb)

ab.sort(reverse=True)

abk=ab[:k]

ans=[]

for item in abk:
    for cc in c:
        ans.append(item+cc)

ans.sort(reverse=True)

for item in ans[:k]:
    print(item)

Submission status: Accepted

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

A = sorted(list(map(int, input().split())))
B = sorted(list(map(int, input().split())))
C = sorted(list(map(int, input().split())))[::-1]

A_B = []
for a in A:
    for b in B:
        A_B.append(a + b)

A_B = sorted(A_B)[::-1][:K]

ans = []
for a_b in A_B:
    for c in C:
        ans.append(a_b + c)

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

Submission status: Accepted

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

A = sorted(list(map(int, input().split())))
B = sorted(list(map(int, input().split())))
C = sorted(list(map(int, input().split())))[::-1]

A_B = []
for a in A:
    for b in B:
        A_B.append(a + b)

A_B = sorted(A_B)

def bin_search(mid):
    res = 0
    idx = 0
    ans = [] 
    for c in C:
        while idx < len(A_B):
            if c + A_B[idx] >= mid:
                res += len(A_B) - idx
                ans.append((c, idx))
                break
            else:
                idx += 1

    return res, ans

ok = 0
ng = pow(10, 10) * 3 + 1

while ok + 1 < ng:
    mid = (ok + ng) // 2
    res, ans = bin_search(mid)
    if res >= K:
        ok = mid
    else:
        ng = mid

res, ans = bin_search(ok)

tmp_ans = []
for c, idx in ans:
    for i in range(idx, len(A_B)):
        tmp_ans.append(A_B[i] + c)
for ans in sorted(tmp_ans)[::-1][:K]:
    print(ans)

Submission status: Accepted

Solution code:
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.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)


def calc(p):
    cnt = 0
    for a in A:
        for b in B:
            for c in C:
                if a + b + c < p:
                    break
                cnt += 1
                if cnt >= K:
                    return True
    return False


end = A[0] + B[0] + C[0] + 1
start = 0
while end - start > 1:
    mid = (end + start)//2
    if calc(mid):
        start = mid
    else:
        end = mid

D = []

for a in A:
    for b in B:
        for c in C:
            if a + b + c < start:
                break
            D.append(a + b + c)
D.sort(reverse=True)
for d in D[:K]:
    print(d)

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.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
D = []
for i in range(X):
    for j in range(Y):
        for k in range(Z):
            if i * j * k > K:
                break
            D.append(A[i] + B[j] + C[k])
D.sort(reverse=True)
for d in D[:K]:
    print(d)

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

D = []
for a in A:
    for b in B:
        D.append(a + b)
D.sort(reverse=True)
if len(D) > K:
    D = D[:K]
E = []
for d in D:
    for c in C:
        E.append(c + d)

E.sort(reverse=True)
for i, e in enumerate(E):
    if i >= K:
        break
    print(e)

Submission status: Accepted

Solution code:
import heapq

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)

checked = {(0, 0, 0)}
h = [(-(A[0] + B[0] + C[0]), 0, 0, 0)]


def push(i, j, k):
    if i < X and j < Y and k < Z and (i, j, k) not in checked:
        heapq.heappush(h, (-(A[i] + B[j] + C[k]), i, j, k))
        checked.add((i, j, k))


for _ in range(K):
    s, i, j, k = heapq.heappop(h)
    print(-s)
    push(i + 1, j, k)
    push(i, j + 1, k)
    push(i, j, k + 1)

Submission status: Accepted

Solution code:
import heapq
X, Y, Z, K = map(int, 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)

done = {(0, 0, 0)}

hq = [(-(A[0]+B[0]+C[0]), 0, 0, 0)]
heapq.heapify(hq)  # リストhqのheap化

ans = 0
D = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]

for _ in range(K):
    s, i, j, k = heapq.heappop(hq)  # heap化されたリストhqから最小値を削除＆その最小値を出力
    print(-s)
    for d in D:
        ni, nj, nk = i+d[0], j+d[1], k+d[2]
        if ni < X and nj < Y and nk < Z and (ni, nj, nk) not in done:
            # heap化されたリストhqに要素xを追加
            heapq.heappush(hq, (-(A[ni]+B[nj]+C[nk]), ni, nj, nk))
            done.add((ni, nj, nk))

Submission status: Accepted

Solution code:
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.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)

li = [(-(a[0]+b[0]+c[0]),0,0,0)]

heapq.heapify(li)

for i in range(k):
    ans = heapq.heappop(li)
    print(-ans[0])
    if x > ans[1]+1 and (-(a[ans[1]+1]+b[ans[2]]+c[ans[3]]),ans[1]+1,ans[2],ans[3]) not in li: 
        heapq.heappush(li,(-(a[ans[1]+1]+b[ans[2]]+c[ans[3]]),ans[1]+1,ans[2],ans[3]))
    if y > ans[2]+1 and (-(a[ans[1]]+b[ans[2]+1]+c[ans[3]]),ans[1],ans[2]+1,ans[3]) not in li:
        heapq.heappush(li,(-(a[ans[1]]+b[ans[2]+1]+c[ans[3]]),ans[1],ans[2]+1,ans[3]))
    if z > ans[3]+1 and (-(a[ans[1]]+b[ans[2]]+c[ans[3]+1]),ans[1],ans[2],ans[3]+1) not in li:
        heapq.heappush(li,(-(a[ans[1]]+b[ans[2]]+c[ans[3]+1]),ans[1],ans[2],ans[3]+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()))
C = list(map(int, input().split()))
A = sorted(A, reverse=True)
B = sorted(B, reverse=True)
C = sorted(C, reverse=True)

ab = []
for a in A:
  for b in B:
    ab += [a+b]
ab = sorted(ab, reverse=True)
ab = ab[:X+Y+Z+1]

ans = []
for n in ab:
  for c in C:
    ans += [n+c]
ans = sorted(ans, reverse=True)
for i in range(K):
  print(ans[i])

Submission status: Accepted

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)
 
YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=0):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.size=len(ls)+1
                self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def __str__(self):
        return  str(self.edges)
 
    def dfs(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0):
        q=deque()
        q.append(x)
        v=[-1]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==-1:
                    q.append(nb)
                    v[nb]=func(v[c],nb,d)
        return v
 
    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.size
        self.ETout=[-1]*self.size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]
 
class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1
 
        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][max(0,r-(1<<N))]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]):
            b=a
        return b
    
    def __str__(self):
        return str(self.table[0])
 
    def print(self):
        for i in self.table:
            print(*i)
 
class Comb:
    def __init__(self,n,mo=10**9+7):
        self.fac=[0]*(n+1)
        self.inv=[1]*(n+1)
        self.fac[0]=1
        self.fact(n)
        for i in range(1,n+1):
            self.fac[i]=i*self.fac[i-1]%mo
            self.inv[n]*=i
            self.inv[n]%=mo
        self.inv[n]=pow(self.inv[n],mo-2,mo)
        for i in range(1,n):
            self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
        return
    
    def fact(self,n):
        return self.fac[n]
        
    def invf(self,n):
        return self.inv[n]
 
    def comb(self,x,y):
        if y<0 or y>x:
            return 0
        return self.fac[x]*self.inv[x-y]*self.inv[y]%mo

def dijkstra(edge,st):
    # edge=[[(v_to,dist_to_v),...],[],...]
    # initialize: def: d=dist(st,i), prev=[previous vertex in minimum path], q[]
    n=len(edge)
    d=[(0 if st==i else inf) for i in range(n)]
    prev=[0]*n
    q=[(j,i) for i,j in enumerate(d)]
    heapify(q)
    v=[False]*n
    # calc
    while q:
        dist,cur=heappop(q)
        if v[cur]:
            continue
        v[cur]=True
        for dst,dist in edge[cur]:
            alt=d[cur]+dist
            if alt<d[dst]:
                d[dst]=alt
                prev[dst]=cur
                heappush(q,(alt,dst))
    return d,prev


show_flg=False
show_flg=True
ans=0


x,y,z,k=LI()
a=sorted(LI())[::-1]
b=sorted(LI())[::-1]
c=sorted(LI())[::-1]

def key(p,q,r):
    return p*y*z+q*z+r

used=dict()

Q=[(-(a[0]+b[0]+c[0]),(0,0,0))]
while Q and k>0:
    #show(Q)
    k-=1
    d,(p,q,r)=heappop(Q)
    used[key(p,q,r)]=1
    print(-d)
    if p+1<x:
        if key(p+1,q,r) not in used:
            heappush(Q,(-(a[p+1]+b[q]+c[r]),(p+1,q,r)))
            used[key(p+1,q,r)]=1
    if q+1<y:
        if key(p,q+1,r) not in used:
            heappush(Q,(-(a[p]+b[q+1]+c[r]),(p,q+1,r)))
            used[key(p,q+1,r)]=1
    if r+1<z:
        if key(p,q,r+1) not in used:
            heappush(Q,(-(a[p]+b[q]+c[r+1]),(p,q,r+1)))
            used[key(p,q,r+1)]=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()))
C = list(map(int,input().split()))

# A,B,Cのリストを降順にソート
A.sort(reverse =True)
B.sort(reverse =True)
C.sort(reverse =True)

from heapq import heappush,heappop
hq = []
arg_hash={}
# キューに追加された組み合わせ
val = A[0]+B[0]+C[0]
# valは初期値(最大値)
heappush(hq,(-val,0,0,0))

for i in range(K):
    ans,a,b,c = heappop(hq)
    # heappopで一番大きい値を取り出す
    print(-ans)
    
    arg_a = (a+1,b,c)
    arg_b = (a,b+1,c)
    arg_c = (a,b,c+1)
    # (a,b,c)の次に大きい組み合わせは(a+1,b,c),(a,b+1,c),(a,b,c+1)のいずれか
    
    if a<X-1 and arg_a not in arg_hash:
        arg_hash[arg_a] = 1
        heappush(hq,(-(A[a+1]+B[b]+C[c]),)+arg_a)
    if b<Y-1 and arg_b not in arg_hash:
        arg_hash[arg_b] = 1
        heappush(hq,(-(A[a]+B[b+1]+C[c]),)+arg_b)
    if c<Z-1 and arg_c not in arg_hash:
        arg_hash[arg_c] = 1
        heappush(hq,(-(A[a]+B[b]+C[c+1]),)+arg_c)

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,Cのリストを降順にソート
A.sort(reverse =True)
B.sort(reverse =True)
C.sort(reverse =True)

# A,B,Cを上からp,q,r番目を選択した場合にp*q*rがKより大きい組み合わせがKより上位に来ることはない
# A,B,Cを上から参照していき。p*q*rがK以下の場合はリストにa+b+cを追加，K以上の場合はbreak
D = []
for p in range(1,X+1):
    for q in range(1,Y+1):
        for r in range(1,Z+1):
            if p*q*r<=K:
                D.append(A[p-1]+B[q-1]+C[r-1])
            else:
                break
D.sort(reverse=True)

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

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
def solve():
    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)
    Cake = []
    heapify(Cake)
    for i in range(X):
        for j in range(min(Y,K//(i+1)+1)):
            for k in range(min(Z,K//((i+1)*(j+1))+1)):
                heappush(Cake,-A[i]-B[j]-C[k])
    ans = []
    for i in range(K):
        ans.append(abs(heappop(Cake)))
    return ans
print(*solve(),sep='\n')

Submission status: Accepted

Solution code:
from collections import deque
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from collections import defaultdict,Counter
from bisect import bisect_left,bisect_right
# from math import gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint

INF = float("inf")

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse_flag):
    data.sort(key=lambda x:x[col],reverse=reverse_flag)
    return data

def mymax(data):
    M = -1*float("inf")
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float("inf")
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def mycount(ls,x):
    # lsはソート済みであること
    l = bisect_left(ls,x)
    r = bisect_right(ls,x)
    return (r-l)

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(" ")
        elif type(ls[0])==str:
            print(" ".join(ls))
        elif type(ls[0])==int:
            print(" ".join(map(str,ls)))
        else:
            print("Output Error")
    else:
        if len(ls)==0:
            print("")
        elif type(ls[0])==str:
            print("".join(ls))
        elif type(ls[0])==int:
            print("".join(map(str,ls)))
        else:
            print("Output Error")

def I():
    return int(input())

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

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

def CI(n):
    return [ int(input()) for _ in range(n) ]

def LI(n):
    return [ list(map(int,input().split())) for _ in range(n) ]

def SI():
    return input()

def SMI():
    return input().split()

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

def SCI(n):
    return [ input() for _ in range(n) ]

def SLI(n):
    return [ list(input().split()) for _ in range(n) ]

x,y,z,k = MI()
a = RI()
b = RI()
c = RI()

# a.sort(reverse=True)
# b.sort(reverse=True)
# c.sort(reverse=True)
# M = a[0] + b[0] + c[0]

M = max(a) + max(b) + max(c)

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

ls.sort(reverse=True)

ls = ls[:min(k,x*y)]

ls_ans = []
for i in range(min(k,x*y)):
    for j in range(z):
        ls_ans.append( ls[i] + c[j] )
ls_ans.sort(reverse=True)

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