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 getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
from heapq import heapify, heappop, heappush
from math import sqrt
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

#############
# Main Code #
#############

"""
N, M = getNM()
weight = []
key = []
for _ in range(M):
    a, b = getNM()
    weight.append(a)
    c = getList()
    key.append(c)

dp = [float('inf')] * (1 << N)
dp[0] = 0
for i in range(M):
    bit = 0
    for item in key[i]:
        bit |= (1 << (item - 1))
    for j in range(1 << N):
        dp[j | bit] = min(dp[j | bit], dp[j] + weight[i])

print(dp)
"""

"""
ARC028 B-特別賞
N, K = getNM()
A = getList()
young = [0] * N
# i番目に若い人の順位はyoung[i]位
for i in range(N):
    young[A[i] - 1] = i

A = [-i for i in A]
# Aの前からK個のリストを作る
prized = []
for i in range(K):
    prized.append(A[i])
heapq.heapify(prized)

# K個数字があるうちの最大値（K番目の数字）を取ってくる
now = heapq.heappop(prized)
print(young[-now - 1] + 1)

for i in range(K, N):
    # もし現在のK番目の数字より小さい数字がきたら
    if A[i] > now:
        # prizedリストに混ぜて（計K個入っている）
        heapq.heappush(prized, A[i])
        # 再びK個数字があるうちの最大値（K番目の数字）を取ってくる
        now = heapq.heappop(prized)
        print(young[-now - 1] + 1)
    # もし現在のK番目の数字より小さい数字がきたら捨てる
    else:
        print(young[-now - 1] + 1)
"""

"""
ABC062 D - 3N Numbers
N = getN()
A = getList()

# 前から計算
fore = A[:N]
# 後ろから計算
back = A[2 * N:]
back = [-i for i in back]
for_sum = sum(fore)
back_sum = sum(back)
heapq.heapify(fore)
heapq.heapify(back)

fore_list = []
back_list = []
for i in range(N):
    fore_list.append(for_sum)
    back_list.append(back_sum)
    in_fore = A[N + i]
    heapq.heappush(fore, in_fore)
    out_fore = heapq.heappop(fore)
    for_sum += in_fore - out_fore

    in_back = (-1) * A[-N - i - 1]
    heapq.heappush(back, in_back)
    out_back = heapq.heappop(back)
    back_sum += in_back - out_back

fore_list.append(for_sum)
back_list.append(back_sum)

ans = -float('inf')
for i in range(N + 1):
    opt = fore_list[i] + back_list[N - i]
    ans = max(ans, opt)
print(ans)
"""

X, Y, Z, K = getNM()
A = sorted([-i for i in getList()])
B = sorted([-i for i in getList()])
C = sorted([-i for i in getList()])

pos = []
heapify(pos)
dict = defaultdict(int)
u = (A[0] + B[0] + C[0], 0, 0, 0)
heappush(pos, u)
dict[u] = 1

for i in range(K):
    p, i, j, l = heappop(pos)
    print(-p)
    # 取り出すごとにA, B, Cについての次の値をpush
    if i + 1 < X:
        opt_a = (A[i + 1] + B[j] + C[l], i + 1, j, l)
        if dict[opt_a] == 0:
            heappush(pos, opt_a)
            dict[opt_a] = 1
    if j + 1 < Y:
        opt_b = (A[i] + B[j + 1] + C[l], i, j + 1, l)
        if dict[opt_b] == 0:
            heappush(pos, opt_b)
            dict[opt_b] = 1
    if l + 1 < Z:
        opt_c = (A[i] + B[j] + C[l + 1], i, j, l + 1)
        if dict[opt_c] == 0:
            heappush(pos, opt_c)
            dict[opt_c] = 1

Submission status: Accepted

Solution code:
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)
AB=[]
for a in A:
    for b in B:
        AB.append(a+b)
AB=sorted(AB,reverse=True)[:K]
ans=[]
for ab in AB:
    for c in C:
        ans.append(ab+c)
ans=sorted(ans,reverse=True)[:K]
print(*ans,sep='\n')

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

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=sorted(list(map(int,input().split())))[::-1]

d=sorted([q+p for q in a for p in b],reverse=True)[:K]

e=sorted([q+p for q in d for p in c],reverse=True)[:K]
for i in e:
  print(i)

Submission status: Accepted

Solution code:
from heapq import*

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

h=[]
se=set((0,0,0))
#ans=[]
heappush(h,(-a[0]-b[0]-c[0],0,0,0))

for _ in range(K):
#  print(h)
  
  
  
  tmp,xx,yy,zz=heappop(h)
  print(-tmp)
  for i in range(2):
    for j in range(2):
      for k in range(2):
        if i+j+k==1:
          xn,yn,zn=xx+i,yy+j,zz+k
          if xn>=x:continue
          if yn>=y:continue
          if zn>=z:continue
          if (xn,yn,zn) in se:
            continue 
          heappush(h,(-a[xn]-b[yn]-c[zn],xn,yn,zn))
          se.add((xn,yn,zn))

Submission status: Accepted

Solution code:
import sys
import math
import copy
from heapq import heappush, heappop, heapify
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
# sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)


def solve():
    x, y, z, k = getList()
    an = getList()
    bn = getList()
    cn = getList()

    ans = []
    for aa in an:
        for bb in bn:
            ans.append(aa + bb)

    ans.sort(reverse=True)
    ans = ans[:k]
    anans = []
    for aa in ans:
        for bb in cn:
            anans.append(aa + bb)

    anans.sort(reverse=True)
    for aaa in anans[:k]:
        print(aaa)

def main():
    n = getN()
    for _ in range(n):
        solve()

    return
if __name__ == "__main__":
    # main()
    solve()

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


import numpy as np
x,y,z,K = list(map(int, input().split()))
a = np.array(list(map(int, input().split())), dtype=np.int64)
b = np.array(list(map(int, input().split())), dtype=np.int64)
c = np.array(list(map(int, input().split())), dtype=np.int64)
ab = (a + b.reshape(-1,1)).reshape(-1)
ab.sort()
c.sort()
abk = ab[-K:]
ck = c[-K:]
l = (abk + ck.reshape(-1,1)).reshape(-1)
l.sort()
l = l[::-1]
write("\n".join(map(str, l[:K])))

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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 = [(a[i]+b[j]) for i in range(x) for j in range(y)]
ab.sort(reverse=True)
c.sort(reverse=True)
abk = ab[:K]
ck = c[:K]
l = [(abk[i]+ck[j]) for i in range(min(len(abk),K)) for j in range(min(len(ck),K))]
l.sort(reverse=True)
write("\n".join(map(str, l[:K])))

Submission status: Accepted

Solution code:

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

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

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

res.sort(reverse=True)
for i in range(K):
    print(res[i])

Submission status: Accepted

Solution code:

from heapq import heappop, heappush

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)

pq = []
heappush(pq, (-A[0] - B[0] - C[0], 0, 0, 0))
appeared = set((0, 0, 0))

for _ in range(K):
    # Pop maximum value
    val, i, j, k = heappop(pq)
    print(-val)

    # Add next value
    if i + 1 < X and (i + 1, j, k) not in appeared:
        heappush(pq, (-A[i + 1] - B[j] - C[k], i + 1, j, k))
        appeared.add((i + 1, j, k))

    if j + 1 < Y and (i, j + 1, k) not in appeared:
        heappush(pq, (-A[i] - B[j + 1] - C[k], i, j + 1, k))
        appeared.add((i, j + 1, k))

    if k + 1 < Z and (i, j, k + 1) not in appeared:
        heappush(pq, (-A[i] - B[j] - C[k + 1], i, j, k + 1))
        appeared.add((i, j, k + 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()))

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

res.sort(reverse=True)

res2 = []
for v in res[:K]:
    for c in C:
        res2.append(v + c)

res2.sort(reverse=True)
for i in range(K):
    print(res2[i])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
(x, y, z, k), a, b, c = [[*map(int, o.split())] for o in open(0)]
a.sort(); b.sort(); c.sort()

h = [(-(a[-1] + b[-1] + c[-1]), -1, -1, -1)]
s = set(h)

from heapq import*
def push(i, j, k):
    global s, h
    try:
        t = (- (a[i] + b[j] + c[k]), i, j, k)
    except IndexError:
        return
    if t not in s:
        heappush(h, t)
        s |= {t}

for _ in [0] * k:
    p, i, j, k = heappop(h)
    print(-p)
    push(i, j, k - 1)
    push(i, j - 1, k)
    push(i - 1, j, k)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
(x, y, z, k), a, b, c = [[*map(int, o.split())] for o in open(0)]
a.sort(); b.sort(); c.sort()

p = a[-1] + b[-1] + c[-1]
s, h = {(p, -1, -1, -1)}, [(-p, -1, -1, -1)]

from heapq import*
def push(i, j, k):
    global s, h
    try:
        t = a[i] + b[j] + c[k]
    except IndexError:
        return
    if (t, i, j, k) not in s:
        heappush(h, (-t, i, j, k))
        s |= {(t, i, j, k)}

for _ in [0] * k:
    p, i, j, k = heappop(h)
    print(-p)
    push(i, j, k - 1)
    push(i, j - 1, k)
    push(i - 1, j, k)

Submission status: Accepted

Solution code:
import sys
from heapq import heappush, heappop

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


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

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

    hq = [(-(A[0] + B[0] + C[0]), 0, 0, 0)]
    seen = set()
    ans = []
    while len(ans) < K:
        s, i, j, k = heappop(hq)
        ans.append(-s)
        if i < X - 1 and (i + 1, j, k) not in seen:
            heappush(hq, (-(A[i + 1] + B[j] + C[k]), i + 1, j, k))
            seen.add((i + 1, j, k))
        if j < Y - 1 and (i, j + 1, k) not in seen:
            heappush(hq, (-(A[i] + B[j + 1] + C[k]), i, j + 1, k))
            seen.add((i, j + 1, k))
        if k < Z - 1 and (i, j, k + 1) not in seen:
            heappush(hq, (-(A[i] + B[j] + C[k + 1]), i, j, k + 1))
            seen.add((i, j, k + 1))

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


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 = [0] * (X * Y)
for i in range(X):
  for j in range(Y):
    AB[i * Y + j] = A[i] + B[j]

AB = sorted(AB, reverse = True)[:K]
#print(AB)
ABC = []
for i in range(len(AB)):
  for j in range(Z):
    ABC.append(AB[i] + C[j])
    
ABC = sorted(ABC, reverse = True)[:K]

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

Submission status: Accepted

Solution code:
from itertools import product
X, Y, Z, K = map(int, input().split())
AB = []
for ab in product(map(int, input().split()), map(int, input().split())):
    AB.append(ab[0] + ab[1])
AB.sort(reverse=True)
AB = AB[:min(K,X*Y)]
ABC = []
for abc in product(AB, map(int, input().split())):
    ABC.append(abc[0]+abc[1])
ABC.sort(reverse=True)
for i in range(K):
    print(ABC[i])

Submission status: Accepted

Solution code:
from itertools import product
X, Y, Z, K = map(int, input().split())
AB = []
for ab in product(map(int, input().split()), map(int, input().split())):
    AB.append(ab[0] + ab[1])
AB.sort(reverse=True)
AB = AB[:K]
ABC = []
for abc in product(AB, map(int, input().split())):
    ABC.append(abc[0]+abc[1])
ABC.sort(reverse=True)
for i in range(K):
    print(ABC[i])

Submission status: Accepted

Solution code:
def binary_search_int(ok, ng, test, k, A, B):
    """
    :param ok: solve(x) = True を必ず満たす点
    :param ng: solve(x) = False を必ず満たす点
    """
    while abs(ok - ng) > 1:
        mid = (ok + ng) // 2
        if test(mid, k, A, B):
            ok = mid
        else:
            ng = mid
    return ok

def get_cnt(x, A, B):
    """ a+b>=x となるようなAの要素とBの要素の組の数 (A, Bはソート済み)"""
    l, r = bisect_left(B, x-A[-1]), len(A)-2
    cnt = len(B) - l
    while l < len(B) and r>=0:
        if A[r]+B[l] < x:
            l += 1
        else:
            cnt += len(B) - l
            r -= 1
    return cnt

def test(x, k, A, B):
    return get_cnt(x, A, B) >= k

from bisect 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()
B.sort()
C.sort()

P = []
for k in range(1,K+1):
    tmp = binary_search_int(0, 10**11,test, k, A, B)
    if tmp != 0:
        P.append(tmp)
Q = []
P.sort()
for k in range(1,K+1):
    Q.append(binary_search_int(1, 10**11,test, k, P, C))
print(*Q, sep="\n")

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)
list1=[]
for i in range(X):
  for j in range(Y):
      list1.append(A[i]+B[j])
list1.sort(reverse=True)
list1=list1[:K+1]
list2=[]
for i in range(min(X*Y,K)):
  for j in range(Z):
    list2.append(list1[i]+C[j])
list2.sort(reverse=True)
for i in range(K):
  print(list2[i])

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_pair = []
for a in A:
    for b in B:
        AB_pair.append(a + b)
AB_pair.sort(reverse=True)

ans = []
for total in AB_pair[:3001]:
    for c in C:
        ans.append(total + c)
ans.sort(reverse=True)
print(*ans[:k], sep="\n")

Submission status: Accepted

Solution code:
# O(klog(k))解法 多分...
import sys
from heapq import heappush,heapify,heappop
input = sys.stdin.readline

def make_kth(A, B, k):
    n, m = len(A), len(B)
    q = [(-A[0] - B[0], 0, 0)]
    r=[]
    for _ in range(min(k, n * m)):
        v, s, t = heappop(q)
        r.append(-v)
        if t + 1 < m:
            heappush(q, (-A[s] - B[t + 1], s, t + 1))
        if t == 0 and s + 1 < n:
            heappush(q, (-A[s + 1] - B[0], s + 1, 0))
    return r

def main():
    _, _, _, k = map(int, input().split())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    c = list(map(int, input().split()))

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

    r = make_kth(a, b, k)
    r = make_kth(c, r, k)
    print(*r, sep="\n")

main()

Submission status: Accepted

Solution code:
# O(klog(k))解法 多分...
import sys
from heapq import heappush,heapify,heappop
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()))

def make_kth(A, B):
    n, m = len(A), len(B)
    A.sort(reverse=1)
    B.sort(reverse=1)
    q = [(-A[0] - B[0], 0, 0)]
    r=[]
    for _ in range(min(k, n * m)):
        v, s, t = heappop(q)
        r.append(-v)
        if t + 1 < m:
            heappush(q, (-A[s] - B[t + 1], s, t + 1))
        if t == 0 and s + 1 < n:
            heappush(q, (-A[s + 1] - B[0], s + 1, 0))
    return r

r = make_kth(a, b)
r = make_kth(c, r)
print(*r,sep="\n")

Submission status: Accepted

Solution code:
import sys
from heapq import heappush,heapify,heappop
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()))
d = [i + j for i in a for j in b]
d.sort(reverse=1)
c.sort(reverse=1)
q = [(-d[0] - c[0], 0, 0)]
for _ in range(k):
    v, s, t = heappop(q)
    print(-v)
    if t + 1 < z:
        heappush(q, (-d[s] - c[t + 1], s, t + 1))
    if t == 0 and s + 1 < x * y:
        heappush(q, (-d[s + 1] - c[0], s + 1, 0))

Submission status: Accepted

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

import heapq
V={(0,0,0)}
Q=[(-(A[0]+B[0]+C[0]),0,0,0)]
heapq.heapify(Q)

def isIn(tup):
    return tup[0]<x and tup[1]<y and tup[2]<z

for i in range(k):
    now=heapq.heappop(Q)
    print(-now[0])
    nex=(now[1]+1,now[2],now[3])
    if not nex in V and isIn(nex):
        V.add(nex)
        heapq.heappush(Q,(-(A[nex[0]]+B[nex[1]]+C[nex[2]]),)+nex)
    nex=(now[1],now[2]+1,now[3])
    if not nex in V and isIn(nex):
        V.add(nex)
        heapq.heappush(Q,(-(A[nex[0]]+B[nex[1]]+C[nex[2]]),)+nex)
    nex=(now[1],now[2],now[3]+1)
    if not nex in V and isIn(nex):
        V.add(nex)
        heapq.heappush(Q,(-(A[nex[0]]+B[nex[1]]+C[nex[2]]),)+nex)

Submission status: Accepted

Solution code:
import sys
import heapq

input = sys.stdin.readline


def main():
    X, Y, Z, K = map(int, input().split())
    A = list(map(lambda x: -int(x), input().split()))
    B = list(map(lambda x: -int(x), input().split()))
    C = list(map(lambda x: -int(x), input().split()))

    A.sort()
    B.sort()
    C.sort()

    p_queue = [(A[0] + B[0] + C[0], 0, 0, 0)]
    visited = set()
    visited.add((0, 0, 0))
    ans = []
    while len(ans) < K:
        s, i_A, i_B, i_C = heapq.heappop(p_queue)
        ans.append(-s)
        if i_A < X - 1 and (i_A + 1, i_B, i_C) not in visited:
            visited.add((i_A + 1, i_B, i_C))
            t = s - A[i_A] + A[i_A + 1]
            heapq.heappush(p_queue, (t, i_A + 1, i_B, i_C))
        if i_B < Y - 1 and (i_A, i_B + 1, i_C) not in visited:
            visited.add((i_A, i_B + 1, i_C))
            t = s - B[i_B] + B[i_B + 1]
            heapq.heappush(p_queue, (t, i_A, i_B + 1, i_C))
        if i_C < Z - 1 and (i_A, i_B, i_C + 1) not in visited:
            visited.add((i_A, i_B, i_C + 1))
            t = s - C[i_C] + C[i_C + 1]
            heapq.heappush(p_queue, (t, i_A, i_B, i_C + 1))

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


if __name__ == "__main__":
    main()

Submission status: Accepted

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

cakeList = []
for i in range(1, X + 1):
    for j in range(1, Y + 1):
        for k in range(1, Z + 1):
            if i * j * k <= K:
                cakeList.append(A[i - 1] + B[j - 1] + C[k - 1])
            else:
                break

cakeList.sort(reverse = True)

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

Submission status: Accepted

Solution code:


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


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    X, Y, Z, K = read_ints()
    A = read_ints()
    B = read_ints()
    C = read_ints()
    BC = [b+c for b in B for c in C]
    BC.sort(reverse=True)
    A.sort(reverse=True)
    low, high = 2, max(A)+max(BC)+1
    while high-low > 1:
        min_deliciousness = low+(high-low)//2
        count_k = 0
        i = len(BC)-1
        for a in A:
            while i > -1 and a+BC[i] < min_deliciousness:
                i -= 1
            count_k += (i+1)
        if count_k > K:
            low = min_deliciousness
        else:
            high = min_deliciousness
    answer = []
    for a in A:
        for bc in BC:
            if a+bc < low:
                break
            else:
                answer.append(a+bc)
    answer.sort(reverse=True)
    for a in answer[:K]:
        print(a)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
from heapq import heappop, heappush
def main():
    def push(i, j, k):
        nonlocal ADD, H
        if i >= x or j >= y or k >= z: return
        if (i, j, k) not in ADD:
            heappush(H, (A[i] + B[j] + C[k], i, j, k))
            ADD.add((i, j, k))
    x, y, z, k = map(int, input().split())
    A = sorted(map(lambda x: -int(x), input().split()))
    B = sorted(map(lambda x: -int(x), input().split()))
    C = sorted(map(lambda x: -int(x), input().split()))
    H = []
    ADD = set()
    push(0, 0, 0)
    for _ in range(k):
        ans, i, j, k = heappop(H)
        push(i + 1, j, k)
        push(i, j + 1, k)
        push(i, j, k + 1)
        print(-ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from heapq import heappop, heappush
def main():
    def push(i, j, k):
        nonlocal A, B, C, ADD
        if i >= x or j >= y or k >= z: return
        if (i, j, k) not in ADD:
            heappush(H, (A[i] + B[j] + C[k], i, j, k))
            ADD.add((i, j, k))
    x, y, z, k = map(int, input().split())
    INF = 10 ** 11
    A = sorted(list(map(lambda x: -int(x), input().split())))
    B = sorted(list(map(lambda x: -int(x), input().split())))
    C = sorted(list(map(lambda x: -int(x), input().split())))
    H = []
    ADD = set()
    push(0, 0, 0)
    for _ in range(k):
        ans, i, j, k = heappop(H)
        push(i + 1, j, k)
        push(i, j + 1, k)
        push(i, j, k + 1)
        print(-ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue

# import numpy as np

sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))


# ===CODE===

def main():
    x, y, z, w = ns()
    a = na()
    b = na()
    c = na()

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

    ans = []
    for ai in a:
        for bi in b:
            ans.append(ai + bi)

    ans.sort(reverse=True)
    ans = ans[:3010]

    res = []
    for ci in c:
        for i in range(len(ans)):
            res.append(ci + ans[i])
    res.sort(reverse=True)

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from heapq import heappop, heappush

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

a_list.sort(reverse=True)
b_list.sort(reverse=True)
c_list.sort(reverse=True)

h = []
a = a_list[0]
b = b_list[0]
c = c_list[0]
heappush(h, (-(a + b + c), 0, 0, 0))

key_dict = dict()
key_dict[(0, 0, 0)] = 1

ans_list = []
for i in range(K):
    ans, a, b, c = heappop(h)
    ans_list.append(-ans)
    a1 = (a + 1, b, c)
    b1 = (a, b + 1, c)
    c1 = (a, b, c + 1)
    if a + 1 < X and not a1 in key_dict:
        heappush(h, (-(a_list[a + 1] + b_list[b] + c_list[c]), a + 1, b, c))
        key_dict[(a + 1, b, c)] = 1
    if b + 1 < Y and not b1 in key_dict:
        heappush(h, (-(a_list[a] + b_list[b + 1] + c_list[c]), a, b + 1, c))
        key_dict[(a, b + 1, c)] = 1
    if c + 1 < Z and not c1 in key_dict:
        heappush(h, (-(a_list[a] + b_list[b] + c_list[c + 1]), a, b, c + 1))
        key_dict[(a, b, c + 1)] = 1
for ans in ans_list:
    print(ans)

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

mid = []

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

mid.sort(reverse=True)

ans = []

for i in range(min(k,len(mid))):
    for j in range(z):
        ans.append(mid[i]+c[j])

ans.sort(reverse=True)

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

Submission status: Accepted

Solution code:
X, Y, Z, K = list(map(int, input().split()))
A = sorted(list(map(int, input().split())), reverse=True)
B = sorted(list(map(int, input().split())), reverse=True)
C = sorted(list(map(int, input().split())), reverse=True)
e = []
s = []

for i in A:
    for j in B:
        e.append(i+j)
e = sorted(e, reverse=True)

if K<len(e):
    e = e[0:K]

for i in e:
    for j in C:
        s.append(i+j)

s = sorted(s, reverse=True)

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

Submission status: Accepted

Solution code:
from heapq import heappop,heappush

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)

l=[]
for a in A:
  for b in B:
    l.append(-a-b)

l.sort()
l=l[:K] if len(l)>=K else l+[0]*(K-len(l))
ans=[]
for c in C:
  for i in l:
    heappush(ans,i-c)
    
for i in range(K):
  print(-heappop(ans))

Submission status: Accepted

Solution code:
import sys
import math
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def make_grid(h, w, num): return [[int(num)] * w for _ in range(h)]


def main():
    X, Y, Z, K = NMI()
    A = NLI()
    B = NLI()
    C = NLI()
    AB = []
    for a in A:
        for b in B:
            AB.append(a+b)
    AB.sort(reverse=True)
    C.sort(reverse=True)
    S = []
    for c_idx in range(min(len(C), 3000)):
        for ab_idx in range(min(len(AB), 3000)):
            S.append(C[c_idx] + AB[ab_idx])
    S.sort(reverse=True)
    for i in range(K):
        print(S[i])



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from heapq import *  # heapqライブラリのimport
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)
  a = []
  heapify(a)
  ans = []
  for i in range(X):
    for j in range(Y):
      if (i+1)*(j+1)>K:
        break
      for k in range(Z):
        if (i+1)*(j+1)*(k+1)>K:
          break
        heappush(a,-A[i]-B[j]-C[k])
  for _ in range(K):
    ans.append(-heappop(a))
  return ans
print(*solve(),sep='\n')