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:
from itertools import product
from heapq import 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)
if x * y * z <= 3000:
    lst = sorted([sum(i) for i in product(a,b,c)], reverse=True)
    [print(i) for i in lst[:k]]
    exit()

idx = [0,0,0]
heap = []
xxx = [x,y,z]

aaa = idx[0] if idx[0]+1 >= x else idx[0] + 1
bbb = idx[1] if idx[1]+1 >= y else idx[1] + 1
ccc = idx[2] if idx[2]+1 >= z else idx[2] + 1
heappush(heap, [-(a[aaa] + b[idx[1]] + c[idx[2]]), [1, 0, 0], 0])
heappush(heap, [-(a[idx[0]] + b[bbb] + c[idx[2]]), [0, 1, 0], 1])
heappush(heap, [-(a[idx[0]] + b[idx[1]] + c[ccc]), [0, 0, 1], 2])
print(a[idx[0]] + b[idx[1]] + c[idx[2]])
doc = {}
for _ in range(min(k-1, x*y*z)):
    score, ix, pos = heappop(heap)
    print(-score)
    for i in range(3):
        tmp = ix.copy()
        tmp[i] = ix[i] if ix[i] + 1 >= xxx[i] else ix[i] + 1
        if ','.join(map(str, tmp)) not in doc:
            doc[','.join(map(str, tmp))] = 1
            score = a[tmp[0]] + b[tmp[1]] + c[tmp[2]]
            # print(idx, ix, score, heap)
            heappush(heap, [-score, tmp, i])

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

Submission status: Accepted

Solution code:
import heapq

import itertools

class Heapq:
    def __init__(self, arr, desc=False):
        if desc:
            arr = [-a for a in arr]
        self.sign = -1 if desc else 1
        self.hq = arr
        heapq.heapify(self.hq)

    def pop(self):
        return heapq.heappop(self.hq) * self.sign

    def push(self, a):
        heapq.heappush(self.hq, a * self.sign)

    def top(self):
        return self.hq[0] * self.sign

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

p = itertools.product(A, B)
A_B_list = [sum(v) for v in itertools.product(A, B)]
A_B_list.sort(reverse=True)
A_B_C_list = [sum(v) for v in itertools.product(A_B_list[:3000], C[:3000])]
A_B_C_list.sort(reverse=True)

for ans in A_B_C_list[:K]:
    print(ans)

Submission status: Accepted

Solution code:
def main():
    from collections import defaultdict
    from heapq import heappush, heappop
    import sys

    input = sys.stdin.readline

    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)

    def calc(p, q, r):
        if p >= x or q >= y or r >= z:
            return 0
        return A[p] + B[q] + C[r]

    h = [(-calc(0, 0, 0), (0, 0, 0))]

    ret = []
    used = defaultdict(bool)
    for _ in range(k):
        v, t = heappop(h)
        ret.append(-v)
        for j in range(3):
            indices = list(t)
            indices[j] += 1
            indices = tuple(indices)
            if used[indices]:
                continue
            used[indices] = True
            heappush(h, (-calc(*indices), indices))

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


main()

# O(KlogK)
# https://img.atcoder.jp/abc123/editorial.pdf

Submission status: Accepted

Solution code:
def main():
    import sys

    input = sys.stdin.readline

    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)

    ret = []
    for p, a in enumerate(A, 1):
        for q, b in enumerate(B, 1):
            if p * q > k:
                break
            for r, c in enumerate(C, 1):
                if p * q * r > k:
                    break
                ret.append(a + b + c)
    ret.sort(reverse=True)
    print(*ret[:k], sep='\n')


main()

# O(Klog^3K)
# https://img.atcoder.jp/abc123/editorial.pdf
# Enumerateのindex間違えていた

Submission status: Accepted

Solution code:
def main():
    import sys

    input = sys.stdin.readline

    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)

    ret = []
    for p, a in enumerate(A):
        for q, b in enumerate(B):
            if p * q > k:
                break
            for r, c in enumerate(C):
                if p * q * r > k:
                    break
                ret.append(a + b + c)
    ret.sort(reverse=True)
    print(*ret[:k], sep='\n')


main()

# O(Klog^3K)
# https://img.atcoder.jp/abc123/editorial.pdf

Submission status: Accepted

Solution code:
def main():
    import sys

    input = sys.stdin.readline

    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 = sorted((a + b for a in A for b in B), reverse=True)[:k]
    ret = sorted((ab + c for ab in AB for c in C), reverse=True)[:k]

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


main()

Submission status: Accepted

Solution code:
x, y, z, k = [int(n) for n in input().split()]
va = sorted([int(n) for n in input().split()], reverse=True)
vb = sorted([int(n) for n in input().split()], reverse=True)
xy = min(x*y, k)
vab = (sorted([a + b for a in va for b in vb], reverse=True))[:xy]
vc = sorted([int(n) for n in input().split()], reverse=True)
xyz = min(x*y*z, k)
print(*((sorted([ab + c for ab in vab for c in vc], reverse=True))[:xyz]), sep="\n")

Submission status: Accepted

Solution code:
import sys
import numpy as np

INF = 10 ** 18

def main():
    x, y, z, K = map(int, sys.stdin.readline().split())
    abc = np.array(sys.stdin.read().split(), dtype=np.int64)
    a = np.append(abc[:x], INF)
    b = np.append(abc[x:x + y], INF)
    c = np.append(abc[x + y:x + y+ z], INF)
    a = np.sort(a)[::-1]
    b = np.sort(b)[::-1]
    c = np.sort(c)[::-1]
 
    res = []
    for i in range(1, min(K, x) + 1):
        for j in range(1, min(y, K // i) + 1):
            for k in range(1, min(z, K // (i * j)) + 1):
                res.append(a[i] + b[j] + c[k])

    res = sorted(res, reverse=True)[:K]
    print('\n'.join(map(str, res)))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import numpy as np

def main():
    x, y, z, K = map(int, sys.stdin.readline().split())
    abc = np.array(sys.stdin.read().split(), dtype=np.int64)
    a = abc[:x]
    b = abc[x:x + y]
    c = abc[x + y:x + y+ z]

    ab = np.sort(np.array([a[i] + b for i in range(x)]).reshape(-1))[::-1][:K]
    res = np.sort(np.array([c[i] + ab for i in range(z)]).reshape(-1))[::-1][:K]

    print('\n'.join(map(str, res)))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import numpy as np
from heapq import heappush, heappop


def main():
    x, y, z, K = map(int, sys.stdin.readline().split())
    abc = np.array(sys.stdin.read().split(), dtype=np.int64)
    a = abc[:x]
    b = abc[x:x + y]
    c = abc[x + y:x + y+ z]
    a = np.sort(a)[::-1]
    b = np.sort(b)[::-1]
    c = np.sort(c)[::-1]

    hq = []
    heappush(hq, (-(a[0]+b[0]+c[0]), 0, 0, 0))
    res = []
    added_before = set()
    # setで確認をO(1)でする
    added_before.add((0, 0, 0))

    for _ in range(K):
        sum_deli, i, j, k = heappop(hq)
        res.append(-sum_deli)
        if i < x - 1 and not (i+1, j, k) in added_before:
            heappush(hq, (-(a[i+1]+b[j]+c[k]), i+1, j, k))
            added_before.add((i+1, j, k))
        if j < y - 1 and not (i, j+1, k) in added_before:
            heappush(hq, (-(a[i]+b[j+1]+c[k]), i, j+1, k))
            added_before.add((i, j+1, k))
        if k < z - 1 and not (i, j, k+1) in added_before:
            heappush(hq, (-(a[i]+b[j]+c[k+1]), i, j, k+1))
            added_before.add((i, j, k+1))

    for s_deli in res:
        print(s_deli)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
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]
ans=[]
for a in range(len(A)):
  for b in range(len(B)):
    for c in range(len(C)):
      if (a+1)*(b+1)*(c+1)>K:
        break
      ans.append(A[a]+B[b]+C[c])

ans=sorted(ans)[::-1]
for i in range(min(K,len(ans))):
  print(ans[i])

Submission status: Accepted

Solution code:
#17:57
a,b,c,k = map(int,input().split())
x = list(map(int,input().split()))
y = list(map(int,input().split()))
z = list(map(int,input().split()))
xy = []
for x0 in x:
  for y0 in y:
    xy.append(x0+y0)
xy.sort(reverse=True)
if a * b > 3000:
  xy = xy[:3000]
xyz = []
for xy0 in xy:
  for z0 in z:
    xyz.append(xy0+z0)
xyz.sort(reverse=True)
for i in range(k):
  print(xyz[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)
Q = []
dic = {}
heapq.heappush(Q, (-(A[0] + B[0] + C[0]), 0, 0, 0))
i = 0
while i < K and len(Q) > 0:
    t = heapq.heappop(Q)
    print(-t[0])
    a, b, c = t[1:]
    if a + 1 < X and (a + 2) * (b + 1) * (c + 1) <= K and not (a + 1, b, c) in dic.keys():
        heapq.heappush(Q, (-(A[a + 1] + B[b] + C[c]), a + 1, b, c))
        dic[(a + 1, b, c)] = 1
    if b + 1 < Y and (a + 1) * (b + 2) * (c + 1) <= K and not (a, b + 1, c) in dic.keys():
        heapq.heappush(Q, (-(A[a] + B[b + 1] + C[c]), a, b + 1, c))
        dic[(a, b + 1, c)] = 1
    if c + 1 < Z and (a + 1) * (b + 1) * (c + 2) <= K and not (a, b, c + 1) in dic.keys():
        heapq.heappush(Q, (-(A[a] + B[b] + C[c + 1]), a, b, c + 1))
        dic[(a, b, c + 1)] = 1
    i += 1

Submission status: Accepted

Solution code:
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)
D = []
for i in range(min(K, X)):
    for j in range(min(K, Y)):
        if (i + 1) * (j + 1) > K:
            break
        for k in range(min(K, Z)):
            if (i + 1) * (j + 1) * (k + 1) > K:
                break
            else:

                D.append(A[i] + B[j] + C[k])

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

Submission status: Accepted

Solution code:
import numpy as np

X, Y, Z, K = map(int, input().split())
A = np.array([int(i) for i in input().split()])
B = np.array([int(i) for i in input().split()])
C =np.array([int(i) for i in input().split()])
A = -np.sort(-A) #要チェックや
B = -np.sort(-B)
C = -np.sort(-C)
D = []
for i in range(min(K, X)):
    for j in range(min(K, Y)):
        if (i + 1) * (j + 1) > K:
            break
        for k in range(min(K, Z)):
            if (i + 1) * (j + 1) * (k + 1) > K:
                break
            else:

                D.append(A[i] + B[j] + C[k])

X = np.array(D)
X = -np.sort(-X)
for i in range(K):
    print(X[i])

Submission status: Accepted

Solution code:
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)
answer=[]
for p in range(min(X,K)):
  for q in range(min(Y,K)):
    if p*q>K:
      break
    for r in range(min(Z,K)):
      if p*q*r>K:
        break
      answer +=[A[p]+B[q]+C[r]]
answer.sort()
for i in range(K):
  print(answer[-i-1])

Submission status: Accepted

Solution code:
import heapq


#root.search(x): ◯.data == x のものが存在するある場合それを出力、ない場合Noneを出力
#root.insert(x): ◯.data == xが存在する場合Falseを出力、ない場合◯.data == x なる頂点を作る
#y.to_s(): 頂点yのdataを出力
#y.left_s(): 頂点yのleftを出力(ない場合はNone)

################################################################################
class Avltree:
    def __init__(self,key=None):
        self.key = key
        self.left = None
        self.right = None 
        self.balance = "Even"
    def search(self,key):
        if self.key == None:
            return None
        if self.key > key:
            if self.left == None:
                return None
            else:
                return self.left.search(key)
        if self.key < key:
            if self.right == None:
                return None
            else:
                return self.right.search(key)
        return self # self.key == keyの場合
    def DoubleRightRotation(self):
        tl = self.left
        self.left = tl.right.right
        tl.right.right = self # selfはそのノード
        tlr = tl.right
        tl.right = tlr.left
        tlr.left = tl
        if tlr.balance == "Left":
            tlr.right.balance = "Right"
            tlr.left.balance = "Even"
        elif tlr.balance == "Right":
            tlr.right.balance = "Even"
            tlr.left.balance = "Left"
        elif tlr.balance == "Even":
            tlr.right.balance = "Even"
            tlr.left.balance = "Even"
        tlr.balance = "Even"
        return tlr
    def DoubleLeftRotation(self):
        tr = self.right
        self.right = tr.left.left
        tr.left.left = self
        trl = tr.left
        tr.left = trl.right
        trl.right = tr
        if trl.balance == "Right":
            trl.left.balance = "Left"
            trl.right.balance = "Even"
        elif trl.balance == "Left":
            trl.left.balance = "Even"
            trl.right.balance = "Right"
        elif trl.balance == "Even":
            trl.left.balance = "Even"
            trl.right.balance = "Even"
        trl.balance = "Even"
        return trl
    def SingleLeftRotation(self):
        tr = self.right
        tr.balance = "Even"
        self.balance = "Even"
        self.right = tr.left
        tr.left = self
        return tr
    def SingleRightRotation(self):
        tl = self.left
        tl.balance = "Even"
        self.balance = "Even"
        self.left = tl.right
        tl.right = self
        return tl
    def replace(self,p,v): # 親ノードpの下にある自分(self)をvに置き換える。
        if p.left == self:
            p.left = v
        else :
            p.right = v 
    def insert(self,key): # rootでのみ呼ばれる挿入
        if self.key == None: # rootを含むrotationはしないことにする。
            self.key = key
            return self
        if key < self.key:
            if self.left == None:
                self.left = Avltree(key)
            else:
                self.left.insertx(self,key)
        elif key > self.key:
            if self.right == None:
                self.right = Avltree(key)
            else:
                self.right.insertx(self,key)
        else: # key == self.key:
            pass # do not overwrite
    def insertx(self,p,key): # replaceを呼ぶために一つ上の親を持っているinsert
        if self.key > key:
            if self.left == None:
                self.left = Avltree(key)
            else:
                if not self.left.insertx(self, key): # 左の木が生長しなければ、
                    return False # 成長しない
            if self.balance == "Right":
                self.balance = "Even"
                return False
            elif self.balance == "Even":
                self.balance = "Left"
                return True # 成長した
            elif self.balance == "Left":
                if self.left.balance == "Right":
                    self.replace(p,self.DoubleRightRotation())
                elif self.left.balance == "Left":
                    self.replace(p,self.SingleRightRotation())
                return False # rotationを行うと成長しない
        if self.key < key:
            if self.right == None:
                self.right = Avltree(key)
            else:
                if not self.right.insertx(self, key):
                    return False 
            if self.balance == "Left":
                self.balance = "Even"
                return False
            elif self.balance == "Even":
                self.balance = "Right"
                return True
            elif self.balance == "Right":
                if self.right.balance == "Left": 
                    self.replace(p,self.DoubleLeftRotation())
                elif self.right.balance == "Right":
                    self.replace(p,self.SingleLeftRotation())
                return False
        return False # self.key == keyの時は何もしないので成長もしない 

    def to_s(self):
        return self.key
    def left_s(self):
        if self.left == None:
            return None
        return (self.left).key
    def right_s(self):
        if self.right == None:
            return None
        return (self.right).key


def Search(x,y,z):
    global dict
    global root
    global q
    p = a[x] + b[y] + c[z]
    u = ((1001)**2) * x + ((1001)**1) * y + z
    s = root.search(u)
    if s == None:
        root.insert(u)
        heapq.heappush(q, -p)
        if p not in dict:
            dict[p] = [(x, y, z)]
        else:
            dict[p].append((x, y, z))


x,y,z,k = [int(_) for _ in input().split()]
a = [int(_) for _ in input().split()]
b = [int(_) for _ in input().split()]
c = [int(_) for _ in input().split()]
a = sorted(a)
b = sorted(b)
c = sorted(c)

t = k
root = Avltree()
q = []
heapq.heapify(q)
dict = {}
count = 0
while t != 0:
    if t == k:
        p = a[x-1]+b[y-1]+c[z-1]
        print(p)
        x -= 1
        y -= 1
        z -= 1
        u = ((1001)**2) * x + ((1001)**1) * y + z
        root.insert(u)
        
        if x != 0:
            Search(x-1,y,z)
        if y != 0:
            Search(x,y-1,z)
        if z != 0:
            Search(x,y,z-1)

        if x == 0 and y == 0 and z == 0:
            break
        
        t -= 1
    else:
        p = heapq.heappop(q)*(-1)
        print(p)
        x, y, z = dict[p].pop()

        if x != 0:
            Search(x-1,y,z)
        if y != 0:
            Search(x,y-1,z)
        if z != 0:
            Search(x,y,z-1)

        if x == 0 and y == 0 and z == 0:
            break

        t -= 1

Submission status: Accepted

Solution code:
import heapq
import numpy as np
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()))
flag = np.ones((X,Y,Z),dtype=np.bool)
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)

ABC = []
heapq.heappush(ABC,(-1 * (A[0]+B[0]+C[0]),0,0,0))
flag[0][0][0] = False
ctr = 0
while ctr < K and ABC:
    s,a,b,c = heapq.heappop(ABC)
    print(-s)
    if a+1<X and flag[a+1][b][c]:
        heapq.heappush(ABC,(-1 * (A[a+1]+B[b]+C[c]),a+1,b,c))
        flag[a+1][b][c] = False
    if b+1<Y and flag[a][b+1][c]:
        heapq.heappush(ABC,(-1 * (A[a]+B[b+1]+C[c]),a,b+1,c))
        flag[a][b+1][c] = False
    if c+1<Z and flag[a][b][c+1]:
        heapq.heappush(ABC,(-1 * (A[a]+B[b]+C[c+1]),a,b,c+1))
        flag[a][b][c+1] = False
    ctr += 1

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import heapq

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

    d = []
    heapq.heappush(d, (-(A[0]+B[0]+C[0]), 0, 0, 0)) # heapqにタプルを与えると最初の要素でソートする
    ijk_set = set((0,0,0))

    for _ in range(K):
        tmp, i, j, k = heapq.heappop(d)
        print(-tmp)
        if (i+1,j,k) not in ijk_set and i+1 <= X-1:
            heapq.heappush(d, (-(A[i+1]+B[j]+C[k]), i+1, j, k))
            ijk_set.add((i+1,j,k))
        if (i,j+1,k) not in ijk_set and j+1 <= Y-1:
            heapq.heappush(d, (-(A[i]+B[j+1]+C[k]), i, j+1, k))
            ijk_set.add((i,j+1,k))
        if (i,j,k+1) not in ijk_set and k+1 <= Z-1:
            heapq.heappush(d, (-(A[i]+B[j]+C[k+1]), i, j, k+1))
            ijk_set.add((i,j,k+1))
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    X = int(next(tokens))  # 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:
#!/usr/bin/env python3
import sys


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

    for i in range(X):
        for j in range(Y):
            AB.append(A[i]+B[j])
    AB.sort(reverse=True)
    AB = AB[:K]

    ABC = []
    for k in range(Z):
        for ab_index in range(len(AB)):
            ABC.append(C[k]+AB[ab_index])

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


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    X = int(next(tokens))  # 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:
tmp = list(map(int, input().split()))
x = tmp[0]
y = tmp[1]
z = tmp[2]
k = tmp[3]
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)

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

ansl.sort(reverse=True)

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

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heapify,heappop,heappush
import sys,bisect,math,itertools,string,queue
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

x,y,z,k = inpl()
a = inpl()
b = inpl()
c = inpl()
ab = []
for i in a:
    for j in b:
        ab.append(i+j)
ab.sort(reverse=True)
A = min(x*y,k)
res = []
# print(ab,c)
for i in range(A):
    for j in range(z):
        res.append(ab[i]+c[j])
res.sort(reverse=True)
for i in range(k):
    print(res[i])

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools
sys.setrecursionlimit(10**8)
mod = 10**9+7
mod2 = 998244353
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

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

Submission status: Accepted

Solution code:
import heapq
x, y, z,  k = map(int, input().split())
a = list(int(x) for x in input().split())
b = list(int(x) for x in input().split())
c = list(int(x) for x in input().split())

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

ab_1 = []
for i in a:
    for j in b:
        heapq.heappush(ab_1, -i-j)
key1 = min([k, x*y])
ab_2 = []
for i in range(key1):
    value = heapq.heappop(ab_1)
    ab_2.append(-value)

abc = []
for p in ab_2:
    for q in c:
        heapq.heappush(abc, -p-q)
key2 = min([k, x*y*z])
for i in range(key2):
    value = heapq.heappop(abc)
    print(-value)

Submission status: Accepted

Solution code:
x,y,z,k = map(int,input().split())	

al = list(map(int,input().split()))
bl = list(map(int,input().split()))
cl = list(map(int,input().split()))

al = sorted(al)
bl = sorted(bl)
cl = sorted(cl)
rank = []
flag = False
for xx in range(x-1,-1,-1):
    tmp = al[xx]+bl[-1]+cl[-1]
    if flag and rank[-1] >= tmp:
        break
    for yy in range(y-1, -1, -1):
        tmp = al[xx]+bl[yy]+cl[-1]
        if flag and rank[-1] >= tmp:
            break
        for zz in range(z-1,-1,-1):
            if len(rank) < k:
                rank.append(al[xx]+bl[yy]+cl[zz])
                rank = sorted(rank, reverse=True)
            else:
                tmp = al[xx]+bl[yy]+cl[zz]
                if rank[-1] < tmp:
                    flag = True
                    rank.pop()
                    rank.append(tmp)
                    rank = sorted(rank, reverse=True)
                else:
                    break

for i in rank:
    print(i)

Submission status: Accepted

Solution code:
import heapq
import collections

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)

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

dictionary = collections.defaultdict(bool)
dictionary[(0,0,0)] = True

i = 0

while i<k:
    M = heapq.heappop(heap)
    print(-M[0])
    i += 1
    if not dictionary[(M[1]+1,M[2],M[3])] and M[1]+1<x:
        heapq.heappush(heap,(-(A[M[1]+1]+B[M[2]]+C[M[3]]),M[1]+1,M[2],M[3]))
        dictionary[(M[1]+1,M[2],M[3])] = True
    if not dictionary[(M[1],M[2]+1,M[3])] and M[2]+1<y:
        heapq.heappush(heap,(-(A[M[1]]+B[M[2]+1]+C[M[3]]),M[1],M[2]+1,M[3]))
        dictionary[(M[1],M[2]+1,M[3])] = True
    if not dictionary[(M[1],M[2],M[3]+1)] and M[3]+1<z:
        heapq.heappush(heap,(-(A[M[1]]+B[M[2]]+C[M[3]+1]),M[1],M[2],M[3]+1))
        dictionary[(M[1],M[2],M[3]+1)] = True

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    x,y,z,K=map(int,input().split())
    A=sorted(map(int,input().split()),reverse=1)
    B=sorted(map(int,input().split()),reverse=1)
    C=sorted(map(int,input().split()),reverse=1)

    # 1<=i<=x,1<=j<=y,1<=k<=z のうち、ijk<=Kを全て取得する
    from itertools import product
    ind=[]
    for i in range(1,x+1):
        if(i>K): break
        for j in range(1,y+1):
            if(i*j>K): break
            for k in range(1,z+1):
                if(i*j*k>K): break
                ind.append((i-1,j-1,k-1))

    S=[]
    for i,j,k in ind:
        S.append(A[i]+B[j]+C[k])
    S.sort(reverse=1)
    for i in range(K):
        print(S[i])

resolve()