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:
#!/usr/bin/env python3

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    

    def calc_1000_num(a, b, c):
        return a + (10 ** 3) * b + (10 ** 6) * c
    
    x, y, z, k = mi()
    A = sorted(lmi(), reverse=True)
    B = sorted(lmi(), reverse=True)
    C = sorted(lmi(), reverse=True)

    h = [(- (A[0]+B[0]+C[0]), [0, 0, 0])]
    registered = set()
    registered.add(calc_1000_num(0, 0, 0))

    for _ in range(k):
        minus_delicious, indices = heappop(h)
        a, b, c = indices
        print(- minus_delicious)
        if a + 1 < x and calc_1000_num(a + 1, b, c) not in registered:
            heappush(h, (- (A[a+1]+B[b]+C[c]), [a+1, b, c]))
            registered.add(calc_1000_num(a + 1, b, c))
        if b + 1 < y and calc_1000_num(a, b + 1, c) not in registered:
            heappush(h, (- (A[a]+B[b+1]+C[c]), [a, b+1, c]))
            registered.add(calc_1000_num(a, b + 1, c))
        if c + 1 < z and calc_1000_num(a, b, c + 1) not in registered:
            heappush(h, (- (A[a]+B[b]+C[c+1]), [a, b, c+1]))
            registered.add(calc_1000_num(a, b, c + 1))

    


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import heapq

X, Y, Z , K = map(int, sys.stdin.readline().split())
A = sorted(list(map(int, sys.stdin.readline().split())), reverse=True)
B = sorted(list(map(int, sys.stdin.readline().split())), reverse=True)
C = sorted(list(map(int, sys.stdin.readline().split())), reverse=True)

ans_heapq = []
i = 0
j = 0
k = 0
heapq.heappush(ans_heapq, [-1 * (A[0] + B[0] + C[0]), i, j, k])
ijk_list = [[0, 0, 0]]
            
for _ in range(K):
    ans, i, j, k = heapq.heappop(ans_heapq)
    print(-1 * ans)
    if i < X - 1 and [i + 1, j, k] not in ijk_list:
        abc = -1 * (A[i + 1] + B[j] + C[k])
        heapq.heappush(ans_heapq, [abc, i + 1, j, k])
        ijk_list.append([i + 1, j, k])
    if j < Y - 1 and [i, j + 1, k] not in ijk_list:
        abc = -1 * (A[i] + B[j + 1] + C[k])
        heapq.heappush(ans_heapq, [abc, i, j + 1, k])
        ijk_list.append([i, j + 1, k])
    if k < Z - 1 and [i, j, k + 1] not in ijk_list:
        abc = -1 * (A[i] + B[j] + C[k + 1])
        heapq.heappush(ans_heapq, [abc, i, j, k + 1])
        ijk_list.append([i, j, k + 1])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from itertools import product
import sys
try:
    from typing import List
except ImportError:
    pass


def solve(
        X: int, Y: int, Z: int, K: int,
        A: "List[int]", B: "List[int]", C: "List[int]"):
    z = [0]

    def f(a: "List[int]"):
        nonlocal z
        a.sort(reverse=True)
        z = [zi + ai for zi, ai in product(z, a[:K])]
        z.sort(reverse=True)
        z = z[:K]

    f(A)
    f(B)
    f(C)
    for zi in z:
        print(zi)


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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline

def main():
    X, Y, Z, K = map(int, readline().rstrip().split())
    A = list(map(int, readline().rstrip().split()))
    B = list(map(int, readline().rstrip().split()))
    C = list(map(int, readline().rstrip().split()))

    ab = [a + b for a in A for b in B]
    ab = sorted(ab, reverse=True)[:K]

    abc = [v + c for v in ab for c in C]
    print(*sorted(abc, reverse=True)[:K], sep='\n')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import heapq  # 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.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
dic={}
dic[(0,0,0)]=1
lst =[(-(A[0]+B[0]+C[0]),0,0,0)]
heapq.heapify(lst)
for r in range(K):
 a=lst[0][1]
 b=lst[0][2]
 c=lst[0][3]
 print(lst[0][0]*(-1))
 heapq.heappop(lst)
 if a<X-1 :
  if (a+1,b,c) not in dic:
   heapq.heappush(lst, (-(A[a+1]+B[b]+C[c]),a+1,b,c))
   dic[(a+1,b,c)]=1
 if b<Y-1 :
  if (a,b+1,c) not in dic:
   heapq.heappush(lst, (-(A[a]+B[b+1]+C[c]),a,b+1,c))
   dic[(a,b+1,c)]=1
 if c<Z-1 :
  if (a,b,c+1) not in dic:
   heapq.heappush(lst, (-(A[a]+B[b]+C[c+1]),a,b,c+1))
   dic[(a,b,c+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.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
ans=[]
for i in range(min(X,K)):
 D=int(K/(i+1))+1
 for j in range(min(D,Y,K)):
  E=int(D/(j+1))+1
  for k in range(min(E,Z,K)):
   ans.append(A[i]+B[j]+C[k])
ans.sort(reverse=True)
for i in range(K):
 print(ans[i])

Submission status: Accepted

Solution code:

import heapq


def submit():
    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 get(i, j, k):
        return a[i] + b[j] + c[k], (i, j, k)

    check = set()
    check.add((0, 0, 0))
    ans = [get(0, 0, 0)]
    q = []
    for _ in range(k - 1):
        prev, (i, j, k) = ans[-1]
        
        if i < x - 1:
            new_triple = (i + 1, j, k)
            if new_triple not in check:
                check.add(new_triple)
                s, _ = get(*new_triple)
                heapq.heappush(q, (-s, new_triple))
        
        if j < y - 1:
            new_triple = (i, j + 1, k)
            if new_triple not in check:
                check.add(new_triple)
                s, _ = get(*new_triple)
                heapq.heappush(q, (-s, new_triple))

        if k < z - 1:
            new_triple = (i, j, k + 1)
            if new_triple not in check:
                check.add(new_triple)
                s, _ = get(*new_triple)
                heapq.heappush(q, (-s, new_triple))

        next_s, next_triple = heapq.heappop(q)
        ans.append((-next_s, next_triple))
        # print(ans)

    for s, _ in ans:
        print(s)
        

submit()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
x,y,z,k = map(int,readline().split())
a = [int(i) for i in readline().split()]
b = [int(i) for i in readline().split()]
c = [int(i) for i in readline().split()]
from heapq import heappush,heappop,heapify
a.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)

chk = [(-(a[0]+b[0]+c[0]),0,0,0)]
heapify(chk)
C = set((0,0,0))
ans = []
for i in range(k):
  p,q,r,s = heappop(chk)
  ans.append(-p)
  if not (q+1,r,s) in C and q < x-1:
    C.add((q+1,r,s))
    heappush(chk,(-(a[q+1]+b[r]+c[s]),q+1,r,s))
  if not (q,r+1,s) in C and r < y-1:
    C.add((q,r+1,s))
    heappush(chk,(-(a[q]+b[r+1]+c[s]),q,r+1,s))
  if not (q,r,s+1) in C and s < z-1:
    C.add((q,r,s+1))
    heappush(chk,(-(a[q]+b[r]+c[s+1]),q,r,s+1))
    
for i in ans:
  print(i)

Submission status: Accepted

Solution code:
import heapq

X,Y,Z,K = [int(x) for x in input().split()]
XYZ=[0]*3
for i in range(3):
    XYZ[i]=[int(x)for x in input().split()]
    XYZ[i].sort(reverse=True)


tmp = (-1*(XYZ[0][0]+XYZ[1][0]+XYZ[2][0]),0,0,0)
q = [tmp]
inq = {tmp[1:]}
heapq.heapify(q)

for ik in range(K):
    max = heapq.heappop(q)
    print(-max[0])
    i,j,k = max[1],max[2],max[3]
    #print(-max[0],i,j,k)
    if(not ((i+1,j,k) in inq) and i+1 < X):
        heapq.heappush(q,(-1*(XYZ[0][i+1]+XYZ[1][j]+XYZ[2][k]),i+1,j,k))
        inq.add((i+1,j,k))
    if(not ((i,j+1,k) in inq) and j+1 < Y):
        heapq.heappush(q,(-1*(XYZ[0][i]+XYZ[1][j+1]+XYZ[2][k]),i,j+1,k))
        inq.add((i,j+1,k))
    if(not ((i,j,k+1) in inq) and k+1 < Z):
        heapq.heappush(q,(-1*(XYZ[0][i]+XYZ[1][j]+XYZ[2][k+1]),i,j,k+1))
        inq.add((i,j,k+1))
print()

Submission status: Accepted

Solution code:
from heapq import heapify, heappop, heappush, heappushpop


class PriorityQueue:
    def __init__(self, heap):
        '''
        heap ... list
        '''
        self.heap = heap
        heapify(self.heap)

    def push(self, item):
        heappush(self.heap, item)

    def pop(self):
        return heappop(self.heap)

    def pushpop(self, item):
        return heappushpop(self.heap, item)

    def __call__(self):
        return self.heap

    def __len__(self):
        return len(self.heap)


x, y, z, k = map(int, input().split())
a_ls = list(map(int, input().split()))
b_ls = list(map(int, input().split()))
c_ls = list(map(int, input().split()))

a_ls.sort()
a_ls.reverse()
b_ls.sort()
b_ls.reverse()
c_ls.sort()
c_ls.reverse()

heap = []

q = PriorityQueue(heap)
q.push((-(a_ls[0] + b_ls[0] + c_ls[0]), 0, 0, 0))
considered = set()
for i in range(k):
    val, i, j, k = q.pop()
    print(-val)
    for di, dj, dk in zip([1, 0, 0], [0, 1, 0], [0, 0, 1]):
        ni = i + di
        nj = j + dj
        nk = k + dk
        if ni >= x or nj >= y or nk >= z:
            continue
        if (ni, nj, nk) not in considered:
            considered.add((ni, nj, nk))
            q.push((-(a_ls[ni] + b_ls[nj] + c_ls[nk]), ni, nj, nk))

Submission status: Accepted

Solution code:
from itertools import combinations, product
*_,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,j in product(a,b):
    ab.append(i+j)
ab.sort(reverse=True)
ab = ab[:k]
abc = []
for i,j in product(ab,c):
    abc.append(i+j)

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

Submission status: Accepted

Solution code:
import sys
from heapq import heappush, heappop
def input(): return sys.stdin.readline().strip()

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

    """
    heapqを使う発想は正しかったが、(Ai, *, *)を全てキューに突っ込んで
    Aiを削除しようとしたのが敗因。

    キューの中で(Ai + Bj + Ck)だけではなく(Ai + Bj + Ck, i, j, k)の
    添字まで管理しておけば、最大値を取り出した後にキューに突っ込むのは
        (A(i+1) + Bj + Ck, i+1, j, k)
        (Ai + B(j+1) + Ck, i, j+1, k)
        (Ai + Bj + C(k+1), i, j, k+1)
    の3つだけでよくなる。。。
    """

    q =[(-A[0]-B[0]-C[0], 0, 0, 0)]
    pushed = set([])
    for _ in range(K):
        val, i, j, k = heappop(q)
        print(-val)
        if i < X - 1 and (i+1, j, k) not in pushed:
            heappush(q, (-A[i+1]-B[j]-C[k], i+1, j, k))
            pushed.add((i+1, j, k))
        if j < Y - 1 and (i, j+1, k) not in pushed:
            heappush(q, (-A[i]-B[j+1]-C[k], i, j+1, k))
            pushed.add((i, j+1, k))
        if k < Z - 1 and (i, j, k+1) not in pushed:
            heappush(q, (-A[i]-B[j]-C[k+1], i, j, k+1))
            pushed.add((i, j, k+1))
        #print(q)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from sys import stdin
import heapq
def main():
    #入力
    readline=stdin.readline
    x,y,z,k=map(int,readline().split())
    a=list(map(int,readline().split()))
    a.sort(reverse=True)
    b=list(map(int,readline().split()))
    b.sort(reverse=True)
    c=list(map(int,readline().split()))
    c.sort(reverse=True)

    s={(0,0,0)}
    h=[[-(a[0]+b[0]+c[0]),(0,0,0)]]
    heapq.heapify(h)
    for _ in range(k):
        li=heapq.heappop(h)
        n=-li[0]
        co=li[1]
        print(n)

        if co[0]+1<x:
            co_1=(co[0]+1,co[1],co[2])
            n_1=a[co_1[0]]+b[co_1[1]]+c[co_1[2]]
            n_1=-n_1
            if co_1 not in s:
                heapq.heappush(h,[n_1,co_1])
                s.add(co_1)

        if co[1]+1<y:
            co_2=(co[0],co[1]+1,co[2])
            n_2=a[co_2[0]]+b[co_2[1]]+c[co_2[2]]
            n_2=-n_2
            if co_2 not in s:
                heapq.heappush(h,[n_2,co_2])
                s.add(co_2)

        if co[2]+1<z:
            co_3=(co[0],co[1],co[2]+1)
            n_3=a[co_3[0]]+b[co_3[1]]+c[co_3[2]]
            n_3=-n_3
            if co_3 not in s:
                heapq.heappush(h,[n_3,co_3])
                s.add(co_3)

if __name__=="__main__":
    main()

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)
ans = []
for i in range(x):
    for j in range(y):
        for l in range(z):
            if (i+1) * (j+1) * (l+1) <= k:
                ans.append(a[i] + b[j] + c[l])
            else:
                break
ans.sort(reverse=True)
for i in range(k):
    print(ans[i])

Submission status: Accepted

Solution code:
import collections
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)
big = [(-a[0]-b[0]-c[0],0,0,0)]
heapq.heapify(big)

visited = collections.defaultdict(int)

ans = []
C = 0
while C < k:
    if big[0][1]+1 < len(a) and not visited[(big[0][1]+1,big[0][2],big[0][3])]:
        heapq.heappush(big, (-a[big[0][1]+1]-b[big[0][2]]-c[big[0][3]],big[0][1]+1,big[0][2],big[0][3] ) )
        visited[(big[0][1]+1,big[0][2],big[0][3])] = 1
    if big[0][2]+1 < len(b) and not visited[(big[0][1],big[0][2]+1,big[0][3])]:
        heapq.heappush(big, (-a[big[0][1]]-b[big[0][2]+1]-c[big[0][3]],big[0][1],big[0][2]+1,big[0][3] ) )
        visited[(big[0][1],big[0][2]+1,big[0][3])] = 1
    if big[0][3]+1 < len(c) and not visited[(big[0][1],big[0][2],big[0][3]+1)]:
        heapq.heappush(big, (-a[big[0][1]]-b[big[0][2]]-c[big[0][3]+1],big[0][1],big[0][2],big[0][3]+1 ) )
        visited[(big[0][1],big[0][2],big[0][3]+1)] = 1
    ans.append(heapq.heappop(big))
    C += 1

for i in ans:
    print(-i[0])

Submission status: Accepted

Solution code:
from itertools import product

x, y, z, k = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = list(map(int, input().split()))

AB = []
for (a, b) in product(A, B):
	AB.append(a + b)

AB.sort(reverse=True)

res = []
for (ab, c) in product(AB[:min(3000, x*y*z)], C):
	res.append(ab + c)

res.sort(reverse=True)

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

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:
import numpy as np


def main():
    X, Y, Z, K = list(map(int, input().split(' ')))
    A = np.array(list(map(int, input().split(' '))))
    B = np.array(list(map(int, input().split(' '))))
    C = np.array(list(map(int, input().split(' '))))
    AB = np.array(np.meshgrid(A, B)).T.reshape(-1, 2).sum(axis=1)
    AB[::-1].sort()
    AB = AB[:min([K, X * Y])]
    ABC = np.array(np.meshgrid(AB, C)).T.reshape(-1, 2).sum(axis=1)
    ABC[::-1].sort()
    for ans in ABC[:K]:
        print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

# (sum, idx of a, b, c)

h = []
heapq.heappush(h, (-A[0]-B[0]-C[0], 0, 0, 0))

ans = []
st = set()

for _ in range(K):
    s, i, j, k = heapq.heappop(h)
    ans.append(-s)
    if i+1 < X and not((i+1, j, k) in st):
        heapq.heappush(h, (-A[i+1]-B[j]-C[k], i+1, j, k))
        st.add((i+1, j, k))
    if j+1 < Y and not((i, j+1, k) in st):
        heapq.heappush(h, (-A[i]-B[j+1]-C[k], i, j+1, k))
        st.add((i, j+1, k))
    if k+1 < Z and not((i, j, k+1) in st):
        heapq.heappush(h, (-A[i]-B[j]-C[k+1], i, j, k+1))
        st.add((i, j, k+1))

for v in ans:
    print(v)

Submission status: Accepted

Solution code:
from heapq import heappush, heapify, heappop

def main():
    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)
    
    que = []
    heapify(que)
    heappush(que, (-A[0]-B[0]-C[0], 0, 0, 0))
    s = set()
    
    for i in range(K):
        ans = heappop(que)
        print(-ans[0])
        if(ans[1] < X-1 and not (ans[1]+1, ans[2], ans[3]) in s):
            heappush(que, [-A[ans[1]+1]-B[ans[2]]-C[ans[3]], ans[1]+1, ans[2], ans[3]])
            s.add((ans[1]+1, ans[2], ans[3]))
        if(ans[2] < Y-1 and not (ans[1], ans[2]+1, ans[3]) in s):
            heappush(que, [-A[ans[1]]-B[ans[2]+1]-C[ans[3]], ans[1], ans[2]+1, ans[3]])
            s.add((ans[1], ans[2]+1, ans[3]))
        if(ans[3] < Z-1 and not (ans[1], ans[2], ans[3]+1) in s):
            heappush(que, [-A[ans[1]]-B[ans[2]]-C[ans[3]+1], ans[1], ans[2], ans[3]+1])
            s.add((ans[1], ans[2], ans[3]+1))   
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()))
#a.sort(reverse=True)
#b.sort(reverse=True)
#c.sort(reverse=True)
ab = []
for i in range(x):
    for j in range(y):
        ab.append(a[i] + b[j])
ab.sort(reverse=True)
#print(ab)
ans = []
for i in range(min(k, x*y)):
    for j in range(z):
        ans.append(ab[i] + c[j])
ans.sort(reverse=True)
for i in range(k):
    print(ans[i])

Submission status: Accepted

Solution code:
from heapq import heapify,heappop,heappush

X,Y,Z,K=map(int,input().split())
A=sorted(map(int,input().split()),reverse=True)
B=sorted(map(int,input().split()),reverse=True)
C=sorted(map(int,input().split()),reverse=True)
que=[[-(A[0]+B[0]+C[0]),0,0,0]];heapify(que)
s=set()

for i in range(K):
    p=heappop(que)
    print(-p[0])
    if p[1]<X-1 and not (p[1]+1,p[2],p[3]) in s:
        heappush(que,[-sum([A[p[1]+1],B[p[2]],C[p[3]]]),p[1]+1,p[2],p[3]])
        s.add((p[1]+1,p[2],p[3]))
    if p[2]<Y-1 and not (p[1],p[2]+1,p[3]) in s:
        heappush(que,[-sum([A[p[1]],B[p[2]+1],C[p[3]]]),p[1],p[2]+1,p[3]])
        s.add((p[1],p[2]+1,p[3]))
    if p[3]<Z-1 and not (p[1],p[2],p[3]+1) in s:
        heappush(que,[-sum([A[p[1]],B[p[2]],C[p[3]+1]]),p[1],p[2],p[3]+1])
        s.add((p[1],p[2],p[3]+1))

Submission status: Accepted

Solution code:
import heapq
X, Y, Z, K = map(int,input().split())
A = list(map(lambda x: -1 * int(x),input().split()))
B = list(map(lambda x: -1 * int(x),input().split()))
C = list(map(lambda x: -1 * int(x),input().split()))
A.sort()
B.sort()
C.sort()
Q = []
heapq.heappush(Q, (A[0] + B[0] + C[0], 0, 0, 0))
for _ in range(K):
    SUM, a, b, c = heapq.heappop(Q)
    print(-1 * SUM)
    if a <= X - 2 and not (A[a+1] + B[b] + C[c], a+1, b, c) in Q:
        heapq.heappush(Q, (A[a+1] + B[b] + C[c], a+1, b, c))
    if b <= Y - 2 and not (A[a] + B[b+1] + C[c], a, b+1, c) in Q:
        heapq.heappush(Q, (A[a] + B[b+1] + C[c], a, b+1, c))
    if c <= Z - 2 and not (A[a] + B[b] + C[c+1], a, b, c+1) in Q:
        heapq.heappush(Q, (A[a] + B[b] + C[c+1], a, b, c+1))

Submission status: Accepted

Solution code:
from heapq import heappop, heappush

x, y, z, k = [int(i) for i in input().split()]

a_list = sorted([-int(i) for i in input().split()])
b_list = sorted([-int(i) for i in input().split()])
c_list = sorted([-int(i) for i in input().split()])

hq = []
flag_set = set()

heappush(hq, (a_list[0] + b_list[0] + c_list[0], 0, 0, 0))
flag_set.add((0, 0, 0))
for _ in range(k):
    d, ai, bi, ci = heappop(hq)
    print(-d)
    
    temp = (ai + 1, bi, ci)
    if temp[0] < x and temp not in flag_set:
        heappush(hq, (a_list[ai + 1] + b_list[bi] + c_list[ci], ai + 1, bi, ci))
        flag_set.add(temp)
    
    temp = (ai, bi + 1, ci)
    if temp[1] < y and temp not in flag_set:
        heappush(hq, (a_list[ai] + b_list[bi + 1] + c_list[ci], ai, bi + 1, ci))
        flag_set.add(temp)

    temp = (ai, bi, ci + 1)
    if temp[2] < z and temp not in flag_set:
        heappush(hq, (a_list[ai] + b_list[bi] + c_list[ci + 1], ai, bi, ci + 1))
        flag_set.add(temp)

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

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)


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

ans.sort(reverse=True)

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

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

x, y, z, k = map(int, readline().split())
a = list(map(int, readline().split()))
b = list(map(int, readline().split()))
c = list(map(int, read().split()))
ab = [0] * x * y
for i, aa in enumerate(a):
    for j, bb in enumerate(b):
        ab[i * y + j] = aa + bb
ab = sorted(ab, reverse=True)[:k]
c = sorted(c, reverse=True)
ans = [0] * k * z
for i, abab in enumerate(ab):
    for j, cc in enumerate(c):
        ans[i * z + j] = abab + cc
ans.sort(reverse=True)
print('\n'.join(map(str, ans[:k])))

Submission status: Accepted

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

print(a[0] + b[0] + c[0])
candidates = []
if x > 1: candidates.append((-(a[1] + b[0] + c[0]), 1, 0, 0))
if y > 1: candidates.append((-(a[0] + b[1] + c[0]), 0, 1, 0))
if z > 1: candidates.append((-(a[0] + b[0] + c[1]), 0, 0, 1))
heapq.heapify(candidates)
popped = {(1, 0, 0): 1,
          (0, 1, 0): 1,
          (0, 0, 1): 1}

for i in range(1, k):
    value, p, q, r = heapq.heappop(candidates)
    print(-value)
    try:
        popped[(p+1, q, r)]
    except:
        if p+1 < x: 
            heapq.heappush(candidates, (-(a[p+1] + b[q] + c[r]), p+1, q, r))
            popped[(p+1, q, r)] = 1
    try:
        popped[(p, q+1, r)]
    except:
        if q+1 < y: 
            heapq.heappush(candidates, (-(a[p] + b[q+1] + c[r]), p, q+1, r))
            popped[(p, q+1, r)] = 1
    try:
        popped[(p, q, r+1)]
    except:
        if r+1 < z: 
            heapq.heappush(candidates, (-(a[p] + b[q] + c[r+1]), p, q, r+1))
            popped[(p, q, r+1)] = 1

Submission status: Accepted

Solution code:
import math
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)
l=[]
#まずX+Yを求め、上から順にソート
#10^6相当の計算
for i in range(X):
    for j in range(Y):
        l.append(A[i] + B[j])
l.sort(reverse=True)
ans=[]
#(X+Y)+Zより、全体の上位を求めるが、Zが何であれ、X+Yの和が上からK番目以下のものは考慮しなくて良い
#(X+YにおいてK+i番目のもの(X+Y)_K+i+Zjが全体でK番以内に食い込めるということは、1~K番目のX+Yにて(X+Y)_1~K+Zj>(X+Y)_K+i+Zjが成立することと矛盾する)
#これで高々10^7相当までのソートでよくなる
for i in range(min(K,len(l))):
    for j in range(Z):
        ans.append(l[i]+C[j])
ans.sort(reverse=True)
for i in range(K):
    print(ans[i])