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:
X, Y, Z, K = [int(_) for _ in input().split()]
As = [int(_) for _ in input().split()]
Bs = [int(_) for _ in input().split()]
Cs = [int(_) for _ in input().split()]

As.sort()
Bs.sort()
Cs.sort()

choice_stack = [(As[-1] + Bs[-1] + Cs[-1], len(As) - 1, len(Bs) - 1, len(Cs) - 1)]
choice_log = set()

j = 0
while True:
    choice_stack.sort()
    chosen_sum, Ai, Bi, Ci = choice_stack.pop()

    print(chosen_sum)

    step_A = (As[max(0, Ai - 1)] + Bs[Bi] + Cs[Ci], max(0, Ai - 1), Bi, Ci)
    step_B = (As[Ai] + Bs[max(0, Bi - 1)] + Cs[Ci], Ai, max(0, Bi - 1), Ci)
    step_C = (As[Ai] + Bs[Bi] + Cs[max(0, Ci - 1)], Ai, Bi, max(0, Ci - 1))

    if not (step_A in choice_log):
        choice_stack.append(step_A)
        choice_log.add(step_A)
    if not (step_B in choice_log):
        choice_stack.append(step_B)
        choice_log.add(step_B)
    if not (step_C in choice_log):
        choice_stack.append(step_C)
        choice_log.add(step_C)

    j += 1
    if j >= K:
        break

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(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
            D.append(A[i] + B[j] + C[k])
            #print(A[i] + B[j] + C[k], i, j, k)
            
D.sort(reverse = True)
for d in D[:K]:
    print(d)

Submission status: Accepted

Solution code:
x,y,z,k=map(int,input().split())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
C=list(map(int,input().split()))
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)

tmp=[]
for a in A:
  for b in B:
    tmp.append(a+b)
tmp.sort(reverse=True)
tmp=tmp[:k+1]

ans=[]
for c in C:
  for t in tmp:
    ans.append(c+t)

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 = 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_list=[]

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

abc_list = list(reversed(sorted(abc_list)))

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

t=[]

for i in a:
    for j in b:
      t.append(i+j)

t.sort(reverse=True)
t=t[:min(k,x*y)]

ans=[]
for i in c:
    for j in t:
      ans.append(i+j)

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

Submission status: Accepted

Solution code:
def main():
    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 = []
    for a in A:
        for b in B:
            AB.append(a + b)
    AB.sort(reverse=True)
    ABC = []
    for i in range(min(K, len(AB))):
        for c in C:
            ABC.append(AB[i] + c)
    ABC.sort(reverse=True)
    for x in ABC[:K]:
        print(x)


main()

Submission status: Accepted

Solution code:
from heapq import heappop, heappush

#input
x,y,z,k=[int(i) for i in 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()]

#sort
a=sorted(a,reverse=True)
b=sorted(b,reverse=True)
c=sorted(c,reverse=True)

q=[]
heappush(q,(-(a[0]+b[0]+c[0]),0,0,0))
s={(0,0,0)}

for n in range(k):
    p,h,i,j=heappop(q)
    
    if  (h+1<x) and ((h+1,i,j) not in s):
        heappush(q,(-(a[h+1]+b[i]+c[j]),h+1,i,j))
        s.add((h+1,i,j))
        
    if  (i+1<y) and ((h,i+1,j) not in s):
        heappush(q,(-(a[h]+b[i+1]+c[j]),h,i+1,j))
        s.add((h,i+1,j))
        
    if  (j+1<z) and ((h,i,j+1) not in s):
        heappush(q,(-(a[h]+b[i]+c[j+1]),h,i,j+1))        
        s.add((h,i,j+1))
        
    print(-p)

Submission status: Accepted

Solution code:
I=lambda:list(map(int,input().split()));k=I()[3];s=lambda a:sorted(i+j for i in I()for j in a)[:-k-1:-1];print(*s(s(I())))

Submission status: Accepted

Solution code:
x,y,z,k=map(int,input().split())
a,b,c=[sorted(list(map(int,input().split())),reverse=True) for i in range(3)]
L=[]
for i in range(x):
    for j in range(y):
        if (i+1)*(j+1)>k:
            break
        for m in range(z):
            if (i+1)*(j+1)*(m+1)>k:
                break
            else:
                L.append(a[i]+b[j]+c[m])
for i in sorted(L,reverse=True)[:k]:
    print(i)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import heapq
x,y,z,k = (int(x) for x in 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)
# heap
h = []
g = set()
heapq.heappush(h, (-(a[0]+b[0]+c[0]),0,0,0))
for i in range(k):
    q,ia,ib,ic = heapq.heappop(h)
    print(-q)
    ja,jb,jc = ia+1,ib,ic
    if ja<x and (ja,jb,jc) not in g:
        heapq.heappush(h, (-(a[ja]+b[jb]+c[jc]),ja,jb,jc))
        g.add((ja,jb,jc))
    ja,jb,jc = ia,ib+1,ic
    if jb<y and (ja,jb,jc) not in g:
        heapq.heappush(h, (-(a[ja]+b[jb]+c[jc]),ja,jb,jc))
        g.add((ja,jb,jc))
    ja,jb,jc = ia,ib,ic+1
    if jc<z and (ja,jb,jc) not in g:
        heapq.heappush(h, (-(a[ja]+b[jb]+c[jc]),ja,jb,jc))
        g.add((ja,jb,jc))

Submission status: Accepted

Solution code:
x,y,z,q=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 bisect(l,r):
  cnt=(l+r)//2
  if cnt==l:
    return l-1+judge(l)
  if judge(cnt):
    return bisect(cnt+1,r)
  else:
    return bisect(l,cnt)
def judge(thr):
  m=0
  for i in range(x):
    for j in range(y):
      if i*j>q:
        break
      for k in range(z):
        if i*j*k>q or a[i]+b[j]+c[k]<thr:
          break
        m+=1
        if m>=q:
          return True
  return False
def make(thr):
  m=0
  l=[]
  for i in a:
    for j in b:
      for k in c:
        n=i+j+k
        if n<thr+1:
          break
        m+=1
        l+=[n]
  l.sort(reverse=True)
  return l+[thr]*(q-len(l))
thr=bisect(0,a[0]+b[0]+c[0]+1)
ans=make(thr)
for w in ans:
  print(w)

Submission status: Accepted

Solution code:
from sys import stdin
from heapq import heappush, heappop

def ria(sep = ''):
    if sep == '' :
        return list(map(int, input().split())) 
    else: return list(map(int, input().split(sep)))
def rsa(sep = ''):
    if sep == '' :
        return input().split() 
    else: return input().split(sep)
def ri(): return int(input())
def rd(): return float(iuput())
def rs(): return input()

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

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

hp = []
heappush(hp, (-(A[0] + B[0] + C[0]), 0, 0, 0))
hs = set()
hs.add((0, 0, 0))
for k in range(K):
    p = heappop(hp)
    print(p[0] * -1)
    ix = p[1]
    iy = p[2]
    iz = p[3]
    if (ix + 1 < X) and ((ix + 1, iy, iz) not in hs):
        hs.add((ix + 1, iy, iz))
        heappush(hp,(-(A[ix + 1] + B[iy] + C[iz]), ix + 1, iy, iz))
    if iy + 1 < Y and ((ix, iy + 1, iz) not in hs):
        hs.add((ix, iy + 1, iz))
        heappush(hp,(-(A[ix] + B[iy + 1] + C[iz]), ix, iy + 1, iz))
    if iz + 1 < Z and ((ix, iy, iz + 1) not in hs):
        hs.add((ix, iy, iz + 1))
        heappush(hp,(-(A[ix] + B[iy] + C[iz + 1]), ix, iy, iz + 1))

Submission status: Accepted

Solution code:
def d_cake_123_priority_queue(X, Y, Z, K, A, B, C):
    # editionalの解法3
    import heapq
    # 数列A, B, Cを降順ソート
    a, b, c = sorted(A, reverse=True), sorted(B, reverse=True), sorted(C, reverse=True)

    def evaluation(x, y, z):
        # heapqは最小値を取り出す方式なので、符号を反転させないといけない
        return (-(a[x] + b[y] + c[z]), x, y, z)

    # priority queue を定義し、(A_1 + B_1 + C_1, 1, 1, 1) を追加
    q = []
    heapq.heappush(q, evaluation(0, 0, 0))
    ans = []
    memo = {(0, 0, 0): True}

    # priority queueに対するK回の操作の部分
    for _ in range(K):
        e, x, y, z = heapq.heappop(q)
        ans.append(-e)
        if x + 1 < X and (x + 1, y, z) not in memo:
            heapq.heappush(q, evaluation(x + 1, y, z))
            memo[(x + 1, y, z)] = True
        if y + 1 < Y and (x, y + 1, z) not in memo:
            heapq.heappush(q, evaluation(x, y + 1, z))
            memo[(x, y + 1, z)] = True
        if z + 1 < Z and (x, y, z + 1) not in memo:
            heapq.heappush(q, evaluation(x, y, z + 1))
            memo[(x, y, z + 1)] = True
    return '\n'.join(map(str, ans[:K]))

X, Y, Z, K = [int(i) for i in 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()]
print(d_cake_123_priority_queue(X, Y, Z, K, A, B, C))

Submission status: Accepted

Solution code:
def d_cake_123_priority_queue(X, Y, Z, K, A, B, C):
    # editionalの解法3
    import heapq
    # 数列A, B, Cを降順ソート
    a, b, c = sorted(A, reverse=True), sorted(B, reverse=True), sorted(C, reverse=True)

    def evaluation(x, y, z):
        # heapqは最小値を取り出す方式なので、符号を反転させないといけない
        return (-(a[x] + b[y] + c[z]), x, y, z)

    # priority queue を定義し、(A_1 + B_1 + C_1, 1, 1, 1) を追加
    q = []
    heapq.heappush(q, evaluation(0, 0, 0))
    ans = []

    # priority queueに対するK回の操作の部分
    for _ in range(K):
        (e, x, y, z) = heapq.heappop(q)
        ans.append(-e)
        if x + 1 < X and evaluation(x + 1, y, z) not in q:
            heapq.heappush(q, evaluation(x + 1, y, z))
        if y + 1 < Y and evaluation(x, y + 1, z) not in q:
            heapq.heappush(q, evaluation(x, y + 1, z))
        if z + 1 < Z and evaluation(x, y, z + 1) not in q:
            heapq.heappush(q, evaluation(x, y, z + 1))
    return '\n'.join(map(str, ans[:K]))

X, Y, Z, K = [int(i) for i in 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()]
print(d_cake_123_priority_queue(X, Y, Z, K, A, B, C))

Submission status: Accepted

Solution code:
xyzk_, *nums_ = [input() for _ in range(4)]

*le, k = [int(w) for w in xyzk_.split()]
abc = [sorted((int(n) for n in w.split()), reverse=True) for w in nums_]

p = [0, 0, 0]
pool = [0, sum(abc[i][p[0]] for i in range(3))]
for _ in range(k):
    max_pool = max(pool)
    max_t = 0
    for i in range(3):
        if p[i] + 1 == le[i]:
            continue
        t = abc[i][p[i] + 1] + abc[(i + 1) % 3][0] + abc[(i + 2) % 3][0]
        if t > max_t:
            max_t = t
            max_3 = i
    if max_pool < max_t:
        p[max_3] = min(p[max_3] + 1, le[max_3] - 1)
        j, k = (max_3 + 1) % 3, (max_3 + 2) % 3
        for n1 in abc[j][:p[j] + 1]:
            for n2 in abc[k][:p[k] + 1]:
                pool.append(n1 + n2 + abc[max_3][p[max_3]])
    print(pool.pop(pool.index(max(pool))))

Submission status: Accepted

Solution code:
def d_cake_123_sort_modified(X, Y, Z, K, A, B, C):
    # editionalの解法1
    ab = sorted([a + b for b in B for a in A], reverse=True)[:K]
    ans = sorted([e + c for e in ab for c in C], reverse=True)[:K]
    return ' '.join(map(str, ans))

X, Y, Z, K = [int(i) for i in 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()]
print(d_cake_123_sort_modified(X, Y, Z, K, A, B, C))

Submission status: Accepted

Solution code:
from heapq import heapify, heappush, heappop


class AscKeyMappedPriorityQueue(object):

    def __init__(self, arr=None, key_generator=lambda x: x):
        """
        昇順以外のソートをheapqで実現することはできず、昇順になるキーを挿入する値から作る必要がある。
        tupleの扱いやらが面倒なのでオブジェクトとしてpush, pop操作を簡易に行えるようにしている。
        :param arr: ヒープ化する元の配列が存在する場合は指定する
        :param key_generator: 挿入する値から昇順になるようなキーを作る関数
        """
        self.key_generator = key_generator
        if arr:
            self.arr = [(key_generator(e), e) for e in arr]
            heapify(self.arr)
        else:
            self.arr = []

    def push(self, e):
        heappush(self.arr, (self.key_generator(e), e))

    def pop(self):
        return heappop(self.arr)[1]


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

A = sorted(A, reverse=True)
B = sorted(B, reverse=True)
C = sorted(C, reverse=True)

considered = set()

q = AscKeyMappedPriorityQueue(key_generator=lambda v: (-v[0], v[1], v[2], v[3]))
q.push((A[0] + B[0] + C[0], 0, 0, 0))
considered.add((0, 0, 0))

for _ in range(K):
    e, a, b, c = q.pop()
    print(e)
    if not (a + 1, b, c) in considered and len(A) > a + 1:
        q.push((A[a + 1] + B[b] + C[c], a + 1, b, c))
        considered.add((a + 1, b, c))
    if not (a, b + 1, c) in considered and len(B) > b + 1:
        q.push((A[a] + B[b + 1] + C[c], a, b + 1, c))
        considered.add((a, b + 1, c))
    if not (a, b, c + 1) in considered and len(C) > c + 1:
        q.push((A[a] + B[b] + C[c + 1], a, b, c + 1))
        considered.add((a, b, c + 1))

Submission status: Accepted

Solution code:
"""
python3 main.py < input.txt
"""
import math
import itertools as it
import heapq

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

def evaluate(x,y,z): return (-A[x]-B[y]-C[z], x,y,z)

Q=[]
heapq.heappush(Q, evaluate(0,0,0))
for i in range(1,K+1):
    (e,x,y,z) = heapq.heappop(Q)
    print(-e)
    if x+1 < X and evaluate(x+1, y, z) not in Q:
        heapq.heappush(Q, evaluate(x+1, y, z))
    if y+1 < Y and evaluate(x, y+1, z) not in Q:
        heapq.heappush(Q, evaluate(x, y+1, z))
    if z+1 < Z and evaluate(x, y, z+1) not in Q:
        heapq.heappush(Q, evaluate(x, y, z+1))

Submission status: Accepted

Solution code:
x,y,z,k = map(int,input().split())
xlist = list(map(int,input().split()))
ylist = list(map(int,input().split()))
zlist = list(map(int,input().split()))
xlist.sort(reverse=True)
ylist.sort(reverse=True)
zlist.sort(reverse=True)
xlist[k:] = []
ylist[k:] = []
zlist[k:] = []
ans = []
for i in xlist:
     for j in ylist:
          ans.append(i+j)
ans.sort(reverse=True)
ans[k:]=[]
Ans = []
for i in ans:
     for j in zlist:
          Ans.append(i+j)
Ans.sort(reverse=True)
Ans[k:]=[]
for i in Ans:
     print(i)

Submission status: Accepted

Solution code:
S=sorted;I=lambda:S(map(int,input().split()));k=I()[3];s=lambda a,b:S(i+j for i in a for j in b)[:-k-1:-1];print(*s(s(I(),I()),I()))

Submission status: Accepted

Solution code:
import itertools

X, Y, Z, K = tuple([int(x) for x in str(input()).split(' ')])

A = sorted([int(x) for x in str(input()).split(' ')], reverse=True)
B = sorted([int(x) for x in str(input()).split(' ')], reverse=True)
C = sorted([int(x) for x in str(input()).split(' ')], reverse=True)

tmp = {(0, 0, 0) : A[0] + B[0] + C[0]}
tmp_keys = [(0, 0 ,0)]
out = []

for i in range(K):
    (a, b, c),  p = max(tmp.items(), key=lambda x : x[1])
    out.append(tmp.pop((a, b, c)))

    keys = []
    if a < X - 1:
        keys.append((a+1, b, c))
    if b < Y - 1:
        keys.append((a, b+1, c))
    if c < Z - 1:
        keys.append((a, b, c+1))
    
    for key in keys:
        if key not in tmp_keys:
            tmp[key] = A[key[0]] + B[key[1]] + C[key[2]]
            tmp_keys.append(key)

for x in out:
    print(x)

Submission status: Accepted

Solution code:
def d_cake_123_sort_all(X, Y, Z, K, A, B, C):
    # editionalの解法2
    a, b, c = sorted(A, reverse=True), sorted(B, reverse=True), sorted(C, reverse=True)
    ans = []
    for i, a_i in enumerate(a, 1):
        for j, b_j in enumerate(b, 1):
            for k, c_k in enumerate(c, 1):
                if i * j * k <= K:
                    ans.append(a_i + b_j + c_k)
                else:
                    break
    ans.sort(reverse=True)
    return '\n'.join(map(str, ans[:K]))

X, Y, Z, K = [int(i) for i in 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()]
print(d_cake_123_sort_all(X, Y, Z, K, A, B, C))

Submission status: Accepted

Solution code:
import numpy as np
import itertools

X, Y, Z, K = tuple([int(x) for x in str(input()).split(' ')])

A = np.array(sorted([int(x) for x in str(input()).split(' ')], reverse=True))
B = np.array(sorted([int(x) for x in str(input()).split(' ')], reverse=True))
C = np.array(sorted([int(x) for x in str(input()).split(' ')], reverse=True))

tmp = {(0, 0, 0) : A[0] + B[0] + C[0]}
tmp_keys = [(0, 0 ,0)]
out = []

for i in range(K):
    (a, b, c),  p = max(tmp.items(), key=lambda x : x[1])
    out.append(tmp.pop((a, b, c)))

    keys = []
    if a < X - 1:
        keys.append((a+1, b, c))
    if b < Y - 1:
        keys.append((a, b+1, c))
    if c < Z - 1:
        keys.append((a, b, c+1))
    
    for key in keys:
        if key not in tmp_keys:
            tmp[key] = A[key[0]] + B[key[1]] + C[key[2]]
            tmp_keys.append(key)

for x in out:
    print(x)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

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)

ABC = []

for x in range(X):
    for y in range(Y):
        if (x + 1) * (y + 1) > K:
            break
        for z in range(Z):
            if (x + 1) * (y + 1) * (z + 1) > K:
                break
            ABC.append(A[x] + B[y] + C[z])

ABC = sorted(ABC, reverse=True)
ABC = ABC[:K]

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

Submission status: Accepted

Solution code:
import math
import sys

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

x=sorted(list(map(int,input().split())),reverse=True)
y=sorted(list(map(int,input().split())),reverse=True)
z=sorted(list(map(int,input().split())),reverse=True)



"""
if X*Y*Z<=3000:
    ans=[]
    for i in range(X):
        for j in range(Y):
            for k in range(Z):  ans.append(x[i]+y[j]+z[k])
    ans.sort()
    for i in range(min(3000,X*Y*Z)):
        print(ans[i])
    sys.exit()
"""

ans=[]
for i in range(min(X,K)):
    tmp1=math.ceil(K/(i+1))
    for j in range(min(Y,tmp1)):
        tmp2=math.ceil(tmp1/(j+1))
        for k in range(min(Z,tmp2)):
            ans.append(x[i]+y[j]+z[k])

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys
from heapq import heappush, heappop

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

X,Y,Z,K=MAP()
A=sorted(LIST(), reverse=True)
B=sorted(LIST(), reverse=True)
C=sorted(LIST(), reverse=True)


que=[]
heappush(que, (-(A[0]+B[0]+C[0]), 0, 0, 0))
S={(0,0,0)}
for i in range(K):
    ans=heappop(que)
    print(-ans[0])
    a,b,c=ans[1:]
    if a+1<X and (a+1,b,c) not in S:
        heappush(que, (-(A[a+1]+B[b]+C[c]), a+1, b, c))
        S.add((a+1,b,c))
    if b+1<Y and (a,b+1,c) not in S:
        heappush(que, (-(A[a]+B[b+1]+C[c]), a, b+1, c))
        S.add((a,b+1,c))
    if c+1<Z and (a,b,c+1) not in S:
        heappush(que, (-(A[a]+B[b]+C[c+1]), a, b, c+1))
        S.add((a,b,c+1))

Submission status: Accepted

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

ab = sorted(x+y for x in a for y in b)[:-k-1:-1]
abc = sorted(x+y for x in ab[:k] for y in c)[:-k-1:-1]
print(*abc, sep='\n')

Submission status: Accepted

Solution code:
import numpy as np
import sys

X, Y, Z, K = map(int, input().split())
a = np.array(list(map(int, sys.stdin.readline().split())), dtype='int64')
b = np.array(list(map(int, sys.stdin.readline().split())), dtype='int64')
c = np.array(list(map(int, sys.stdin.readline().split())), dtype='int64')

d = (a + b.reshape([len(b), 1])).flatten()
d.sort()
e = (d[-K:] + c.reshape([len(c), 1])).flatten()
e.sort()

for ec in e[-K:][::-1]:
    print(ec)

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)

li = []
ans = []

for i in a:
    for j in b:
        li.append(i + j)
        
li.sort(reverse = True)
li = li[:min(k,x*y)]

for i in c:
    for j in li:
        ans.append(i + j)
        
ans.sort(reverse = True)

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

Submission status: Accepted

Solution code:
from heapq import heappop, heappush
from time import time

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)
A.append(-float('inf'))
B.sort(reverse=True)
B.append(-float('inf'))
C.sort(reverse=True)
C.append(-float('inf'))

hq = []
count = 0
queued = set()
heappush(hq,(-(A[0]+B[0]+C[0]),time(),0,0,0))
queued.add((0,0,0))
while True:
  d,_,i,j,k = heappop(hq)
  #print(-d,i,j,k)
  print(-d)
  count += 1
  if count >= K:
    break
  for l in [i,i+1]:
    for m in [j,j+1]:
      for n in [k,k+1]:
        if (l,m,n) in queued:
          continue
        else:
          heappush(hq,(-(A[l]+B[m]+C[n]),time(),l,m,n))
          queued.add((l,m,n))

Submission status: Accepted

Solution code:
#!/usr/bin/python3

import numpy as np
import itertools

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

    a_add_b = np.array(list(A + j for j in B))
    a_add_b = np.sort(a_add_b, axis=None)

    e_add_c = np.array(list(C + j for j in a_add_b[:-K-1:-1]))
    e_add_c = np.sort(e_add_c, axis=None)


    for abc in e_add_c[:-K-1:-1]:
        print(abc)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from heapq import heappush, heappop

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)

h = []
minus_value = -(A[0] + B[0] + C[0])
heappush(h, (minus_value, 0, 0, 0))
searched = set()
cnt = 0
while cnt < K:
    minus_value, ia, ib, ic = heappop(h)
    if (ia, ib, ic) in searched:
        continue
    cnt += 1
    searched.add((ia, ib, ic))
    print(-minus_value)
    if ia < X - 1:
        heappush(h, (minus_value + A[ia] - A[ia + 1], ia + 1, ib, ic))
    if ib < Y - 1:
        heappush(h, (minus_value + B[ib] - B[ib + 1], ia, ib + 1, ic))
    if ic < Z - 1:
        heappush(h, (minus_value + C[ic] - C[ic + 1], ia, ib, ic + 1))

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

X,Y,Z,K=MAP()
A=sorted(LIST(), reverse=True)
B=sorted(LIST(), reverse=True)
C=sorted(LIST(), 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:
def main():
  x,y,z,k=map(int,input().split())
  al=[int(i) for i in input().split()]
  bl=[int(i) for i in input().split()]
  cl=[int(i) for i in input().split()]
  lst=[i+j for i in al for j in bl]
  lst.sort(reverse=True)
  num=min(x*y,k)
  lst=lst[:num]
  L=[i+j for i in cl for j in lst]
  L.sort(reverse=True)
  for i in range(k):
    print(L[i])
if __name__=='__main__':
  main()

Submission status: Accepted

Solution code:
X,Y,Z,K=[int(i) for i in input().split(" ")]
A=[int(i) for i in input().split(" ")]
B=[int(i) for i in input().split(" ")]
C=[int(i) for i in input().split(" ")]
 
AB=[]
 
A=sorted(A,reverse=True)[:K:]
B=sorted(B,reverse=True)[:K:]
C=sorted(C,reverse=True)[:K:]
for a in A:
    for b in B:
        AB.append(a+b)
 
AB=sorted(AB,reverse=True)[:K:]
 
ABC=[]
for ab in AB:
    for c in C:
        ABC.append(ab+c)
 
ABC=sorted(ABC,reverse=True)[:K:]
 
 
for abc in ABC:
    print(abc)

Submission status: Accepted

Solution code:
import re
import numpy as np
import heapq

X, Y, Z, K = [int(item) for item in re.split(r"\s", input())]
A = [int(item) for item in re.split(r"\s", input())]
B = [int(item) for item in re.split(r"\s", input())]
C = [int(item) for item in re.split(r"\s", input())]


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

total = A[0] + B[0] + C[0]

A = [A[0] - a for a in A]
B = [B[0] - b for b in B]
C = [C[0] - c for c in C]

q = [[0, 0, 0, 0]]
heapq.heapify(q)

for _ in range(K):
    val, a_i, b_i, c_i = heapq.heappop(q)
    print(total - val)

    if a_i + 1 <= len(A) - 1:
        c_1 = [A[a_i + 1] + B[b_i] + C[c_i], a_i + 1, b_i, c_i]
        if c_1 not in q:
            heapq.heappush(q, c_1)
    if b_i + 1 <= len(B) - 1:
        c_2 = [A[a_i] + B[b_i + 1] + C[c_i], a_i, b_i + 1, c_i]
        if c_2 not in q:
            heapq.heappush(q, c_2)
    if c_i + 1 <= len(C) - 1:
        c_3 = [A[a_i] + B[b_i] + C[c_i + 1], a_i, b_i, c_i + 1]
        if c_3 not in q:
            heapq.heappush(q, c_3)

Submission status: Accepted

Solution code:
from heapq import *

Q=[]
teast=[]
X,Y,Z,K=list(map(int,input().split(" ")))

for i in range(3):
    teast.append(list(map(int,input().split(" "))))

A=sorted(teast[0],reverse=True)
B=sorted(teast[1],reverse=True)
C=sorted(teast[2],reverse=True)

arg_hash={}
heappush(Q,(-A[0]-B[0]-C[0],0,0,0))
arg_hash[(0,0,0)]=1

for k in range(K):
    ans=heappop(Q)
    a,b,c=ans[1:]
    print(-ans[0])
    argA=(a+1,b,c)
    if a <X-1 and( not argA in arg_hash):
        arg_hash[argA]=1
        heappush(Q,(-A[a+1]-B[b]-C[c],)+argA)
    argB=(a,b+1,c)
    if b <Y-1 and( not argB in arg_hash):
        arg_hash[argB]=1
        heappush(Q,(-A[a]-B[b+1]-C[c],)+argB)
    argC=(a,b,c+1)
    if c <Z-1 and( not argC in arg_hash):
        arg_hash[argC]=1
        heappush(Q,(-A[a]-B[b]-C[c+1],)+argC)