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:
import heapq


XYZK = 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)

hq = []
pushed = []
heapq.heappush(hq, (-(A[0]+B[0]+C[0]), 0, 0, 0))
for _ in range(XYZK[3]):
    a = heapq.heappop(hq)
    print(-a[0])
    i, j, k = a[1:]
    if i < XYZK[0]-1:
        if not (i+1, j, k) in pushed:
            heapq.heappush(hq, (-(A[i+1]+B[j]+C[k]), i+1, j, k))
            pushed.append((i+1, j, k))
    if j < XYZK[1]-1:
        if not (i, j+1, k) in pushed:
            heapq.heappush(hq, (-(A[i]+B[j+1]+C[k]), i, j+1, k))
            pushed.append((i, j+1, k))
    if k < XYZK[2]-1:
        if not (i, j, k+1) in pushed:
            heapq.heappush(hq, (-(A[i]+B[j]+C[k+1]), i, j, k+1))
            pushed.append((i, j, k+1))

Submission status: Accepted

Solution code:
import bisect

X,Y,Z,K = list(map(int,input().split()))
AA = list(map(int,input().split()))
BB = list(map(int,input().split()))
CC = list(map(int,input().split()))
MAX = max(max(AA),max(BB),max(CC))

AB = []
for a in AA:
  for b in BB:
    AB.append(a+b)
    
AB.sort()
XY = len(AB)

def check(n):
  cnt = 0
  for c in CC:
    cnt += (XY - bisect.bisect_left(AB,n-c))
  return cnt >= K

OK = 0
NG = MAX*3+100
while NG - OK >1:
  mid = (OK+NG)//2
  if check(mid):
    OK = mid
  else:
    NG = mid
    
    
ans = []
for c in CC:
    n = bisect.bisect_left(AB,OK-c)
    for i in range(n,XY):
      ans.append(c+AB[i])
      
ans.sort(reverse=True)
for YUI in range(K):
  print(ans[YUI])

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
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)
hp = []
heappush(hp, (-(a[0] + b[0] + c[0]), 0, 0, 0))
used = {(0, 0, 0):1}
for _ in range(k):
    ans, d, e, f = heappop(hp)
    print(-ans)
    if(d + 1 < x and not (d + 1, e, f) in used):
        heappush(hp, (-(a[d + 1] + b[e] + c[f]), d + 1, e, f))
        used[(d + 1, e, f)] = 1
    if(e + 1 < y and not (d, e + 1, f) in used):
        heappush(hp, (-(a[d] + b[e + 1] + c[f]), d, e + 1, f))
        used[(d, e + 1, f)] = 1
    if(f + 1 < z and not (d, e, f + 1) in used):
        heappush(hp, (-(a[d] + b[e] + c[f + 1]), d, e, f + 1))
        used[(d, e, f + 1)] = 1

Submission status: Accepted

Solution code:
# https://www.kumilog.net/entry/python-speed-comp#input-%E3%81%A8-sysstdinreadline
# https://teratail.com/questions/88396

from heapq import heapify, heappush, heappop
import sys

input = sys.stdin.readline


# 入力速度を速める

class Data:
    def __init__(self, value, indices):
        self.value = value
        self.indices = indices

    def __lt__(self, other):
        return self.value < other.value


# ケーキの美味しさの合計とそのときの組み合わせ
# heapqで比較できるようにltを作る

X, Y, Z, K = map(int, input().split())
a = map(int, input().split())
b = map(int, input().split())
c = map(int, input().split())

a = list(sorted(a, reverse=True))
b = list(sorted(b, reverse=True))
c = list(sorted(c, reverse=True))
# 降順ソート

hq = []
heapify(hq)

t = a[0] + b[0] + c[0]
t *= -1
# 各リストの初項を合計すると美味しさ最大の組み合わせになる
# heapqは最小をheappopするので、
# 符号反転させて、最大が出るようにする
# ただし、print時に再度符号反転必要

d = Data(t, (0, 0, 0))
heappush(hq, d)

dtpls = ((1, 0, 0), (0, 1, 0), (0, 0, 1))
# 1,2,3のキャンドルのインデックスの追加量のタプルのリスト
# ループを回し、順番に美味しさの合計が大きい組み合わせの美味しさ合計を出力する
# その後、出力した合計から、
# 1,2,3の形のキャンドルつきのケーキのインデックスのうち
# 一つのインデックスを１増やしたもの（最大3通り）を
# heapqに追加する

st = set()
# ケーキの組み合わせタプルで既出なものを貯めておく集合

cnt = 0
for _ in range(K):
    d = heappop(hq)
    print(-d.value)
    for dtpl in dtpls:
        na = d.indices[0] + dtpl[0]
        if na >= X: continue
        nb = d.indices[1] + dtpl[1]
        if nb >= Y: continue
        nc = d.indices[2] + dtpl[2]
        if nc >= Z: continue
        # 1,2,3のインデックスのどれかが用意された種類数を超えていたら、
        # そのインデックスの組み合わせはありえないので、次の候補に移る
        ntpl = (na, nb, nc)
        if ntpl in st: continue
        # 既にheapqに追加済みの組み合わせは、重複追加しないで、次の候補に移る

        nt = a[na] + b[nb] + c[nc]
        nt *= - 1
        # 美味しさの合計は符号反転させる
        heappush(hq, Data(nt, ntpl))
        st.add(ntpl)
        # heapqに追加済みなので、集合にaddする

Submission status: Accepted

Solution code:
# https://www.kumilog.net/entry/python-speed-comp#input-%E3%81%A8-sysstdinreadline
# https://teratail.com/questions/88396

from heapq import heapify, heappush, heappop
import sys

input = sys.stdin.readline


class Data:
    def __init__(self, value, indices):
        self.value = value
        self.indices = indices

    def __lt__(self, other):
        return self.value < other.value


X, Y, Z, K = map(int, input().split())
a = map(int, input().split())
b = map(int, input().split())
c = map(int, input().split())

a = list(sorted(a, reverse=True))
b = list(sorted(b, reverse=True))
c = list(sorted(c, reverse=True))

hq = []
heapify(hq)

t = a[0] + b[0] + c[0]
t *= -1

d = Data(t, (0, 0, 0))

heappush(hq, d)

dtpls = ((1, 0, 0), (0, 1, 0), (0, 0, 1))

st = set()

cnt = 0
for _ in range(K):
    d = heappop(hq)
    print(-d.value)
    for dtpl in dtpls:
        na = d.indices[0] + dtpl[0]
        if na >= X: continue
        nb = d.indices[1] + dtpl[1]
        if nb >= Y: continue
        nc = d.indices[2] + dtpl[2]
        if nc >= Z: continue

        nt = a[na] + b[nb] + c[nc]
        nt *= - 1

        ntpl = (na, nb, nc)
        if ntpl in st: continue
        heappush(hq, Data(nt, ntpl))
        st.add(ntpl)

Submission status: Accepted

Solution code:
# https://img.atcoder.jp/abc123/editorial.pdf
# 問題D: Cake 123 解法 #3 - さらに高速な解法、priority-queue を用いて O(K log K)

from heapq import heappush, heappop

def solve(X, Y, Z, K, A, B, C):
    def append(cand_a, cand_b, cand_c):
        cand_key = (cand_a, cand_b, cand_c)
        if not cand_key in pushedQ \
                and cand_a < len(A) \
                and cand_b < len(B) \
                and cand_c < len(C):
            yum = A[cand_a] + B[cand_b] + C[cand_c]
            heappush(Q, (-yum, cand_key))
            pushedQ.append(cand_key)

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

    Q = []
    a = 0
    b = 0
    c = 0
    yum = A[a] + B[b] + C[c]
    heappush(Q, (-yum, (a, b, c)))
    pushedQ = [(a, b, c)]

    for _ in range(K):
#       print(Q)
        max_q = heappop(Q)
        max_yum, max_key = max_q[0] * (-1), max_q[1]
        a, b, c = max_key
        print(max_yum)
        append(a+1, b, c)
        append(a, b+1, c)
        append(a, b, c+1)

if __name__ == "__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()))
    solve(X, Y, Z, K, A, B, C)

Submission status: Accepted

Solution code:
def int_raw():
    return int(input())

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

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

X,Y,Z,K = ints_raw()

A = ints_raw()
B= ints_raw()
C= ints_raw()
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
def main():
    D = [a+b for a in A for b in B]
    D.sort(reverse=True)
    D = D[:K+1]
    E =[d+c for d in D for c in C]
    E.sort(reverse=True)
    for e in range(K):
        print (E[e])

main()

Submission status: Accepted

Solution code:
from itertools import product

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)

ab = [ai + bi for (ai, bi) in product(a[:k], b[:k])]
ab.sort(reverse=True)
abc = [abi + ci for (abi, ci) in product(ab[: min(k, x * y * z)], c[:k])]
abc.sort(reverse=True)

for abci in abc[: min(k, x * y * z)]:
    print(abci)

Submission status: Accepted

Solution code:
from itertools import product

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)

a = []
count = 0
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
            a.append(A[i] + B[j] + C[k])

a.sort(reverse=True)

for i in range(K):
    print(a[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)

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

for a in sorted(ans,reverse=True)[:K]:
    print(a)

Submission status: Accepted

Solution code:
import heapq


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)
    q = []
    heapq.heappush(q, (-(A[0] + B[0] + C[0]), 0, 0, 0))
    pushed = set([0, 0, 0])
    for _ in range(K):
        total, a, b, c = heapq.heappop(q)
        print(-total)
        if a + 1 < X and (a+1, b, c) not in pushed:
            heapq.heappush(q, (total + A[a] - A[a+1], a+1, b, c))
            pushed.add((a+1, b, c))
        if b + 1 < Y and (a, b+1, c) not in pushed:
            heapq.heappush(q, (total + B[b] - B[b+1], a, b+1, c))
            pushed.add((a, b+1, c))
        if c + 1 < Z and (a, b, c+1) not in pushed:
            heapq.heappush(q, (total + C[c] - C[c+1], a, b, c+1))
            pushed.add((a, b, c+1))


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()))
ans = []
A.sort()
A.reverse()
B.sort()
B.reverse()
C.sort()
C.reverse()
for i in range(min(K,len(A))):
	if K // (i+1) > 0:
		for j in range(min(K // (i+1),len(B))):
			if K // ((i+1) * (j+1)) > 0:
				for l in range(min(K // ((i+1) * (j+1)),len(C))):
					ans.append(A[i] + B[j] + C[l])

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

Submission status: Accepted

Solution code:
x,y,z,k = map(int, raw_input().split())
a = map(int, raw_input().split())
b = map(int, raw_input().split())
c = map(int, raw_input().split())
s = []
a.sort(reverse = True)
b.sort(reverse = True)
c.sort(reverse = True)
for ka in range(x):
    for kb in range(y):
			s.append(a[ka]+b[kb])
s.sort(reverse = True)
p = 3000
if(x * y < 3000):
	p = x * y
t = []
for n in range(p):
	for m in c:
		t.append(s[n] + m)
t.sort(reverse = True)
for n in range(k):
	print(t[n])

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 = [a + b for a in A for b in B]
AB.sort(reverse=True)
ABC = [ab + c for ab in AB[:K] for c in C[:K]]
ABC.sort(reverse=True)
[print(abc) for abc in ABC[: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 = list(reversed(sorted(a)))
b = list(reversed(sorted(b)))
c = list(reversed(sorted(c)))

abc = []
for p in range(x):
    for q in range(y):
        if (p+1) * (q+1) > k:
            break
        for r in range(z):
            if (p+1) * (q+1) * (r+1) > k:
                break
            abc.append(a[p]+ b[q] + c[r])

abc = list(reversed(sorted(abc)))

for i in range(k):
    print(abc[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)

ABC = []
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
            ABC.append(A[i] + B[j] + C[k])

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

Submission status: Accepted

Solution code:
# https://img.atcoder.jp/abc123/editorial.pdf
# 問題D: Cake 123 解法 #2 - 「ある条件」を満たす最大106307通りを全部ソート

def solve(X, Y, Z, K, A, B, C):
    A.sort(reverse=True)
    B.sort(reverse=True)
    C.sort(reverse=True)

    ABC = []
    for i1, a in enumerate(A, start=1):
       for i2, b in enumerate(B, start=1):
           for i3, c in enumerate(C, start=1):
               if i1 * i2 * i3 <= K:
                   ABC.append(a + b + c)
               else:
                   break
    ABC.sort(reverse=True)
    ABC = ABC[:K]

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

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

Submission status: Accepted

Solution code:
import sys

if __name__ == "__main__":
    (X, Y, Z, K) = list(map(int, sys.stdin.readline().split()))
    A = list(map(int, sys.stdin.readline().split()))
    B = list(map(int, sys.stdin.readline().split()))
    C = list(map(int, sys.stdin.readline().split()))

    A.sort(reverse=True)
    B.sort(reverse=True)
    C.sort(reverse=True)
    v = []
    for a in range(len(A)):
        for b in range(len(B)):
            if (a + 1) * (b + 1) > K:
                break
            for c in range(len(C)):
                if (a + 1) * (b + 1) * (c + 1) > K:
                    break
                v.append(A[a] + B[b] + C[c])

    v.sort(reverse=True)

    for i in range(K):
        sys.stdout.write("%d\n" % v[i])

Submission status: Accepted

Solution code:
# https://img.atcoder.jp/abc123/editorial.pdf 解法 #1 - 工夫したソートで O(K^2 log K)

def solve(X, Y, Z, K, A, B, C):
    AB = []
    [AB.append(a + b) for a in A for b in B]
    AB.sort(reverse=True)
    AB = AB[:K]

    ABC = []
    [ABC.append(ab + c) for ab in AB for c in C]
    ABC.sort(reverse=True)
    ABC = ABC[:K]

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

if __name__ == "__main__":
    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)
    solve(X, Y, Z, K, A, B, C)

Submission status: Accepted

Solution code:

def conKey(i, j, k):
    return str(i)+'-'+str(j)+'-'+str(k)


def getKey(s):
    return map(int, s.split('-'))


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)

h = []
stack = set([])
ans = []
i, j, k = 0, 0, 0
heapq.heappush(h, (-(A[i]+B[j]+C[k]), conKey(i, j, k)))
stack.add(conKey(i, j, k))
for _ in range(K):
    tmp, key = heapq.heappop(h)
    print(-tmp)
    i, j, k = getKey(key)
    key_0 = [i, j, k]

    for m in range(3):
        key_tmp = key_0.copy()
        if key_tmp[m] >= (X, Y, Z)[m] - 1:
            continue
        key_tmp[m] += 1
        tmp_sum = A[key_tmp[0]] + B[key_tmp[1]] + C[key_tmp[2]]

        str_key = conKey(*key_tmp)

        if str_key not in stack:
            heapq.heappush(h, (-tmp_sum, str_key))
            stack.add(str_key)

Submission status: Accepted

Solution code:
import sys
import math
sys.setrecursionlimit(20000000)
input = sys.stdin.readline
x,y,z,p = 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()
"""
if x*y*z <= 3*10**6:
    abc = []
    for i in range(x):
        for j in range(y):
            for k in range(z):
                abc.append(a[i]+b[j]+c[k])
    abc.sort()
    abc = abc[::-1]
    for i in range(p):
        print(abc[i])  
    exit()
"""
ab = []
for i in range(x):
    for j in range(y):
        ab.append(a[i]+b[j])
ab.sort()
c = c[::-1]
ab = ab[::-1]
ab.append(-2**62)
ans = []
miru = [0]*z
for i in range(z):
    if i + 1 == z:
        d = -2**60
    else:
        d = c[i+1]+ab[0]
    for j in range(i+1):
        flag = 0
        while ab[miru[j]] + c[j] >= d and (len(ans)<= p or ab[miru[j]] + c[j] >= ans[0]):
             ans.append(ab[miru[j]] + c[j])
             miru[j]+=1
             flag = 1
        if flag and len(ans) <=p+1:
            ans.sort()
ans.sort()
ans = ans[::-1]
for i in range(p):
    print(ans[i])

Submission status: Accepted

Solution code:
from collections import defaultdict

def append(m, printed, cand_a, cand_b, cand_c):
    key = "{}-{}-{}".format(cand_a, cand_b, cand_c)
    key2 = "{}-{}-{}".format(cand_a-1, cand_b, cand_c)
    key3 = "{}-{}-{}".format(cand_a, cand_b-1, cand_c)
    key4 = "{}-{}-{}".format(cand_a, cand_b, cand_c-1)
    if not key in printed \
            and cand_a < len(A) \
            and cand_b < len(B) \
            and cand_c < len(C) \
            and not key in m \
            and not key2 in m \
            and not key3 in m \
            and not key4 in m :
        m[key] = A[cand_a] + B[cand_b] + C[cand_c]
    return m

def solve(X, Y, Z, K, A, B, C):
    a = 0
    b = 0
    c = 0

    n_print = 0
    memo = {}
    printed = defaultdict(lambda: False)
    while True:
        summ = A[a] + B[b] + C[c]
        printed["{}-{}-{}".format(a, b, c)] = True

        print(summ)

        n_print += 1
        if n_print == K:
            break

        memo = append(memo, printed, a+1, b, c)
        memo = append(memo, printed, a, b+1, c)
        memo = append(memo, printed, a, b, c+1)

        max_k = max(memo, key=memo.get)
        a, b, c = max_k.split("-")
        a = int(a)
        b = int(b)
        c = int(c)
            
        memo.pop(max_k)

if __name__ == "__main__":
    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)
    solve(X, Y, Z, K, A, B, C)

Submission status: Accepted

Solution code:
from heapq import heappush, nlargest

def main():
    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()]
    h = []
    for i in A:
        for j in B:
            heappush(h, i + j)
    H = []
    for i in nlargest(K, h):
        for j in C:
            heappush(H, i+j)
    for i in nlargest(K, H):
        print(i)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict

def append(m, printed, cand_a, cand_b, cand_c):
    key = "{}-{}-{}".format(cand_a, cand_b, cand_c)
    key2 = "{}-{}-{}".format(cand_a-1, cand_b, cand_c)
    key3 = "{}-{}-{}".format(cand_a, cand_b-1, cand_c)
    key4 = "{}-{}-{}".format(cand_a, cand_b, cand_c-1)
    if not key in printed \
            and cand_a < len(A) \
            and cand_b < len(B) \
            and cand_c < len(C) \
            and not key in m \
            and not key2 in m \
            and not key3 in m \
            and not key4 in m :
#       print("Appended {}".format(key))
        m[key] = A[cand_a] + B[cand_b] + C[cand_c]
    return m

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)

a = 0
b = 0
c = 0

n_print = 0
#print(A, B, C)
memo = {}
printed = defaultdict(lambda: False)
while True:
    summ = A[a] + B[b] + C[c]
    printed["{}-{}-{}".format(a, b, c)] = True

    print(summ)

#   print(memo.items())
#   print(a, b, c)
#   print("")

    n_print += 1
    if n_print == K:
        break

    memo = append(memo, printed, a+1, b, c)
    memo = append(memo, printed, a, b+1, c)
    memo = append(memo, printed, a, b, c+1)

    max_k = max(memo, key=memo.get)
    a, b, c = max_k.split("-")
    a = int(a)
    b = int(b)
    c = int(c)
        
    memo.pop(max_k)
#   print("Pop {}".format(max_k))

Submission status: Accepted

Solution code:
import sys; sys.setrecursionlimit(50000)
input = sys.stdin.readline

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

import heapq
q = []
S = set()
heapq.heappush(q, (-(A[0]+B[0]+C[0]), 0, 0, 0))
S.add((0, 0, 0))
for _ in range(K):
    p, i, j, k = heapq.heappop(q)
    print(-p)
    if i + 1 < X and not (i+1, j, k) in S:
        heapq.heappush(q, (-(A[i+1]+B[j]+C[k]), i+1, j, k))
        S.add((i+1,j,k))
    if j + 1 < Y and not (i, j+1, k) in S:
        heapq.heappush(q, (-(A[i]+B[j+1]+C[k]), i, j+1, k))
        S.add((i,j+1,k))
    if k + 1 < Z and not (i, j, k+1) in S:
        heapq.heappush(q, (-(A[i]+B[j]+C[k+1]), i, j, k+1))
        S.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()))

A.sort()
B.sort()
sublist = []
for i in range(max(X-K-1, 0), X):
    for j in range(max(Y - K - 1, 0), Y):
        if (X-i)*(Y-j) <= K:
            sublist.append(A[i]+B[j])

sublist.sort()
# print(sublist)
subanslist = sublist[-K::1]
sbsize = len(subanslist)
anslist = []
C.sort()

for num, i in enumerate(subanslist):
    for j in range(max(Z - K - 1, 0), Z):
        if (sbsize-num)*(Z-j) <= K:
            anslist.append(i+C[j])

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

Submission status: Accepted

Solution code:
X,Y,Z,K = map(int,input().split())
A = [i for i in map(int,input().split())]
B = [i for i in map(int,input().split())]
C = [i for i in map(int,input().split())]
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
ABC = []
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
            ABC.append(A[i] +  B[j] + C[k])
ABC.sort(reverse=True)
for i in range(K):
    print(ABC[i])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
input = sys.stdin.readline

# bisect_left(lists, 3)
# bisect_right(lists, 3)

def main():
	X, Y, Z, K = map(int, input().split(" "))
	As = []
	Bs = []
	Cs = []
	As = input().split()
	As = [int(s) for s in As]
	Bs = input().split()
	Bs = [int(s) for s in Bs]
	Cs = input().split()
	Cs = [int(s) for s in Cs]

	As.sort(reverse=True)
	Bs.sort(reverse=True)
	Cs.sort(reverse=True)

	ans1 = []
	for i, val in enumerate(As):
		for j, vol in enumerate(Bs):
			ans1.append(val+vol)

	ans1.sort(reverse=True)
	ans1 = ans1[:3000]

	ans2 = []
	for i, val in enumerate(ans1):
		for j, vol in enumerate(Cs):
			ans2.append(val+vol)

	ans2.sort(reverse=True)
	for i in range(K):
		print(ans2[i])
	
if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
def 解法3優先度付きキュー():
    import heapq
    X,Y,Z,K = [int(_) for _ in input().split()]
    aA = sorted((int(_) for _ in input().split()),reverse=True)
    aB = sorted((int(_) for _ in input().split()),reverse=True)
    aC = sorted((int(_) for _ in input().split()),reverse=True)
    dS=set()
    aAns = [0]*K
    aQ = []
    def fPush(aQ,i,j,k):
        if X <= i :
            i = X-1
        if Y <= j:
            j = Y-1
        if Z <= k:
            k = Z-1
        if (i,j,k) not in dS:
            heapq.heappush(aQ,(-1*(aA[i]+aB[j]+aC[k]),i,j,k))
            dS.add((i,j,k))
    def fPop(aQ):
        iD,i,j,k = heapq.heappop(aQ)
        return (-1*iD,i,j,k)
    fPush(aQ,0,0,0)
    for iU in range(K):
        aAns[iU],i,j,k = fPop(aQ)
        fPush(aQ,i+1,j,k)
        fPush(aQ,i,j+1,k)
        fPush(aQ,i,j,k+1)

    print(*aAns,sep="\n")

解法3優先度付きキュー()

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)
q = []
printed = set()
heapq.heappush(q, (-A[0] - B[0] - C[0], 0, 0, 0))
i = 0
while i < K:
    m = heapq.heappop(q)
    if m in printed:
        continue
    print(-m[0])
    printed.add(m)
    x, y, z = m[1], m[2], m[3]
    if x + 1 < X:
        heapq.heappush(q, (-A[x + 1] - B[y] - C[z], x + 1, y, z))
    if y + 1 < Y:
        heapq.heappush(q, (-A[x] - B[y + 1] - C[z], x, y + 1, z))
    if z + 1 < Z:
        heapq.heappush(q, (-A[x] - B[y] - C[z + 1], x, y, z + 1))
    i += 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.append(-1)
B.append(-1)
C.append(-1)

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

l = []

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

l.sort(reverse = True)

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

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)

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

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

for a in ans:
    print(-a)

Submission status: Accepted

Solution code:
import numpy as np
X, Y, Z, K = map(int, input().split())
x = np.array(list(map(int, input().split())))
y = np.array(list(map(int, input().split())))
z = np.array(list(map(int, input().split())))
l = x.reshape((1,-1)) + y.reshape((-1,1))
l = l.reshape(-1,)
l = np.sort(l)[::-1]
l = l[:K]
l = l.reshape((1,-1)) + z.reshape((-1,1))
l = l.reshape(-1,)
l = np.sort(l)[::-1]
l = l[:K]
for k in range(K):
    print(l[k])