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:
INF = -10**11
x, y, z, k = [int(item) for item in input().split()]
a = sorted([int(item) for item in input().split()], reverse=True) + [INF]
b = sorted([int(item) for item in input().split()], reverse=True) + [INF]
c = sorted([int(item) for item in input().split()], reverse=True) + [INF]

num = x + y + z
ac, bc, cc = 0, 0, 0
ad = a[0] - a[1]
bd = b[0] - b[1]
cd = c[0] - c[1]
kadd = min(12000, x*y*z)
while (ac+1) * (bc+1) * (cc+1) < kadd:
    if ad <= bd and ad <= cd:
        ac += 1
        ad = a[ac] - a[ac+1]
    elif bd <= ad and bd <= cd:
        bc += 1
        bd = b[bc] - b[bc+1]
    elif cd <= ad and cd <= bd:
        cc += 1
        cd = c[cc] - c[cc+1]

for i in range(30):
    if ac+1 < x:
        ac += 1
    if bc+1 < y:
        bc += 1
    if cc+1 < z:
        cc += 1

vals = []
for ai in a[:ac+1]:
    for bi in b[:bc+1]:
        for ci in c[:cc+1]:
            vals.append(ai+bi+ci)
vals.sort(reverse=True)
for i in range(k):
    print(vals[i])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import itertools
import collections
import functools
import math
from queue import Queue
# import numpy as np
INF = float("inf")
import heapq


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

    base = A[0]+B[0]+C[0]
    cand = [[0, 0, 0, 0]]
    heapq.heapify(cand)
    # print(cand)
    for i in range(K):
        a = heapq.heappop(cand)
        for j in range(1, 4):
            if a[j]+1 < XYZ[j-1]:
                b = [a[0]+ABC[j-1][a[j]]-ABC[j-1][a[j]+1],
                     a[1]+int(j == 1),
                     a[2]+int(j == 2),
                     a[3]+int(j == 3)]
                if b not in cand:
                    heapq.heappush(cand, b)
        # print(cand)
        print(base-a[0])
    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:
import sys
from itertools import product

_, _, _, k = [int(v) for v in sys.stdin.readline().split(" ")]
xs = [int(v) for v in sys.stdin.readline().split(" ")]
ys = [int(v) for v in sys.stdin.readline().split(" ")]
zs = [int(v) for v in sys.stdin.readline().split(" ")]


xys = sorted([x + y for x, y in product(xs, ys)], reverse=True)
zs = sorted(zs, reverse=True)
ret = [a + b for a, b in zip([zs[0]] * k, xys)]
for z in zs[1:]:
    rr = ret[:]
    r2 = [a + b for a, b in zip([z] * k, xys)]
    ret = sorted(ret + r2, reverse=True)[:k]
    if ret == rr:
        break
print('\n'.join([str(v) for v in ret]))

Submission status: Accepted

Solution code:
from queue import PriorityQueue
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'))

pq = PriorityQueue()
pq.put((-(A[0]+B[0]+C[0]),0,0,0))
count = 0
queued = set([(0,0,0)])
while True:
  d,i,j,k = pq.get()
  #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:
          pq.put((-(A[l]+B[m]+C[n]),l,m,n))
          queued.add((l,m,n))

Submission status: Accepted

Solution code:
import heapq
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=[]
for a in A:
    for b in B:
        AB.append(a+b)

AB=heapq.nlargest(K,AB)
ABC=[]
for ab in AB:
    for c in C:
        ABC.append(ab+c)

for cake in heapq.nlargest(K,ABC):
    print(cake)

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

AB = []
AC = []
BC = []
for a in A:
    for b in B:
        AB.append(a+b)
    for c in C:
        AC.append(a+c)
for b in B:
    for c in C:
        BC.append(b+c)
AB.sort(reverse=True)
AC.sort(reverse=True)
BC.sort(reverse=True)

hq = []
heapq.heapify(hq)
for a in A:
    for bc in BC[:K]:
        heapq.heappush(hq,-a-bc)
for b in B:
    for ac in AC[:K]:
        heapq.heappush(hq,-b-ac)
for c in C:
    for ab in AB[:K]:
        heapq.heappush(hq,-c-ab)

ans = []
for _ in range(K):
    ans.append(-heapq.heappop(hq))
    heapq.heappop(hq)
    heapq.heappop(hq)

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

Submission status: Accepted

Solution code:
X, Y, Z, K = map(int, input().split())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))
Cs = list(map(int, input().split()))

sum12s = []
for A in As:
    for B in Bs:
        sum12s.append(A+B)
sum12s.sort(reverse=True)
sum12s = sum12s[:K] + [-1]

anss = [] + [-1]
for C in Cs:
    ans2s = []
    iAns = iSum12 = 0
    for _ in range(min(K, len(anss)+len(sum12s)-2)):
        if anss[iAns] >= C+sum12s[iSum12]:
            ans2s.append(anss[iAns])
            iAns += 1
        else:
            ans2s.append(C+sum12s[iSum12])
            iSum12 += 1
    anss = ans2s + [-1]

print('\n'.join(map(str, anss[:-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()))

import heapq

A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
m = A[0]+B[0]+C[0]

counted=set([])
in_heap=set([])

hp = []
heapq.heapify(hp)
heapq.heappush(hp, (0, (0,0,0)))

#print(hp)

for _ in range(K):
  x = heapq.heappop(hp)
  print(m-x[0])
  counted.add(x[1])
  a,b,c = x[1]
  if (a+1, b,c) not in counted and (a+1, b,c) not in in_heap and a<len(A)-1:
    heapq.heappush(hp, (m-A[a+1]-B[b]-C[c], (a+1,b,c)))
    in_heap.add((a+1, b, c))
  if (a, b+1,c) not in counted and (a, b+1,c) not in in_heap and b<len(B)-1:
    heapq.heappush(hp, (m-A[a]-B[b+1]-C[c], (a,b+1,c)))
    in_heap.add((a,b+1,c))
  if (a, b,c+1) not in counted and (a, b,c+1) not in in_heap and c<len(C)-1:
    heapq.heappush(hp, (m-A[a]-B[b]-C[c+1], (a,b,c+1)))
    in_heap.add((a,b,c+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)
A += [-1e10]
B += [-1e10]
C += [-1e10]

memo = [A[i] + B[0] + C[0] for i in range(X + 1)]
L = [[0 for i in range(Y + 1)] for j in range(X + 1)]

for i in range(K):
  ma = 0
  for j in range(X):
    if memo[ma] < memo[j]:
      ma = j
  print(memo[ma])
  mb = 0
  mn = 0
  for j in range(Y):
    x = B[j] + C[L[ma][j]]
    if mb < x:
      mb = x
      mn = j
  L[ma][mn] += 1
  n = 0
  for j in range(Y):
    n = max(n, B[j] + C[L[ma][j]])
  memo[ma] = A[ma] + n

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 = sorted(a)
b = sorted(b)
c = sorted(c)

n = []
heapq.heapify(n)
heapq.heappush(n, (-(a[-1]+b[-1]+c[-1]), 1, 1, 1))
for _ in range(K):
    (m, i, j, k) = heapq.heappop(n)
    print(-m)
    if i + 1 <= x:
        s = (-(a[-i-1]+b[-j]+c[-k]), i+1, j, k)
        if s not in n:
            heapq.heappush(n, s)
    if j + 1 <= y:
        s = (-(a[-i]+b[-j-1]+c[-k]), i, j+1, k)
        if s not in n:
            heapq.heappush(n, s)
    if k + 1 <= z:
        s = (-(a[-i]+b[-j]+c[-k-1]), i, j, k+1)
        if s not in n:
            heapq.heappush(n, s)

Submission status: Accepted

Solution code:
x, y, z, k = map(int, input().split())
alist = list(sorted(map(int, input().split()), key=lambda x: -x)) + [-pow(10, 10)]
blist = list(sorted(map(int, input().split()), key=lambda x: -x)) + [-pow(10, 10)]
clist = list(sorted(map(int, input().split()), key=lambda x: -x)) + [-pow(10, 10)]

setk = set([(0, 0, 0, alist[0] + blist[0] + clist[0])])
outk = set()

for _ in range(k):
  tmpk = None
  tmpi = 0
  for i, _k in enumerate(setk):
    if tmpk is None:
      tmpk = _k
      tmpi = i
    elif tmpk[3] < _k[3]:
      tmpk = _k
      tmpi = i
  print(tmpk[3])
  outk.add(tmpk)
  setk.discard(tmpk)
  if (tmpk[0] + 1, tmpk[1], tmpk[2], tmpk[3] - alist[tmpk[0]] + alist[tmpk[0] + 1]) not in outk:
    setk.add((tmpk[0] + 1, tmpk[1], tmpk[2], tmpk[3] - alist[tmpk[0]] + alist[tmpk[0] + 1]))
  if (tmpk[0], tmpk[1] + 1, tmpk[2], tmpk[3] - blist[tmpk[1]] + blist[tmpk[1] + 1]) not in outk:
    setk.add((tmpk[0], tmpk[1] + 1, tmpk[2], tmpk[3] - blist[tmpk[1]] + blist[tmpk[1] + 1]))
  if (tmpk[0], tmpk[1], tmpk[2] + 1, tmpk[3] - clist[tmpk[2]] + clist[tmpk[2] + 1]) not in outk:
    setk.add((tmpk[0], tmpk[1], tmpk[2] + 1, tmpk[3] - clist[tmpk[2]] + clist[tmpk[2] + 1]))

Submission status: Accepted

Solution code:
import heapq

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

def diff(l):
    m = max(l)
    return sorted(m - v for v in l)[1:]

s = sum(map(max, [a, b, c]))
sa, sb, sc = map(diff, [a, b, c])
da, db, dc = [0], [0], [0]
q = [0]
while k > 0:
    while True:
        if len(sa) > 0 and (len(q) == 0 or q[0] > sa[0]):
            for v in [sa[0] + bb + cc for bb in db for cc in dc]:
                heapq.heappush(q, v)
            da.append(sa[0])
            sa = sa[1:]
        elif len(sb) > 0 and (len(q) == 0 or q[0] > sb[0]):
            for v in [sb[0] + aa + cc for aa in da for cc in dc]:
                heapq.heappush(q, v)
            db.append(sb[0])
            sb = sb[1:]
        elif len(sc) > 0 and (len(q) == 0 or q[0] > sc[0]):
            for v in [sc[0] + aa + bb for aa in da for bb in db]:
                heapq.heappush(q, v)
            dc.append(sc[0])
            sc = sc[1:]
        else:
            break
    v = heapq.heappop(q)
    print s - v
    k -= 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()))
import heapq
q = []
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
def val(i, j, k):
  return -(A[i] + B[j] + C[k])
heapq.heappush(q, (val(0,0,0), 0,0,0))
visited = set((0,0,0))
for _ in range(k):
  v, aa, bb, cc = heapq.heappop(q)
  print(-v)
  if aa + 1 < len(A) and (aa+1, bb, cc) not in visited:
    visited.add((aa+1, bb, cc))
    heapq.heappush(q, (val(aa+1, bb, cc), aa+1, bb, cc))
  if bb + 1 < len(B) and (aa, bb+1, cc) not in visited:
    visited.add((aa, bb+1, cc))
    heapq.heappush(q, (val(aa, bb+1, cc), aa, bb+1, cc))
  if cc + 1 < len(C) and (aa, bb, cc+1) not in visited:
    visited.add((aa, bb, cc+1))
    heapq.heappush(q, (val(aa, bb, cc+1), aa, bb, cc+1))

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [tuple(map(int, l.split())) for l in sys.stdin]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    x,y,z,k = LI()
    a = sorted(LI(), reverse=True)
    b = sorted(LI(), reverse=True)
    c = sorted(LI(), reverse=True)
    u = set()
    q = []
    heapq.heappush(q, (-(a[0]+b[0]+c[0]), 0,0,0))
    u.add((0,0,0))
    r = []
    for _ in range(k):
        t,ai,bi,ci = heapq.heappop(q)
        r.append(-t)
        if ai < x-1:
            nk = (ai+1,bi,ci)
            if nk not in u:
                heapq.heappush(q, (-(a[ai+1]+b[bi]+c[ci]), ai+1,bi,ci))
                u.add(nk)
        if bi < y-1:
            nk = (ai,bi+1,ci)
            if nk not in u:
                heapq.heappush(q, (-(a[ai]+b[bi+1]+c[ci]), ai,bi+1,ci))
                u.add(nk)
        if ci < z-1:
            nk = (ai,bi,ci+1)
            if nk not in u:
                heapq.heappush(q, (-(a[ai]+b[bi]+c[ci+1]), ai,bi,ci+1))
                u.add(nk)

    return '\n'.join(map(str, r))

print(main())

Submission status: Accepted

Solution code:
from collections import defaultdict
import sys
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 = 1)
B.sort(reverse = 1)
C.sort(reverse = 1)
dic = {}
for x in range(1, min(X + 1, K + 1)):
    t = K // x + 1
    for y in range(1, min(Y + 1, t + 1)):
        s = t // y + 1
        for z in range(1, min(Z + 1, s + 1)):
            if (x, y, z) not in dic:
                dic[(x, y, z)] = A[x-1] + B[y-1] + C[z-1]
dic = sorted(dic.values(), reverse = 1)
for i in range(K):
    print(dic[i])

Submission status: Accepted

Solution code:
import heapq


class PriorityQueue:
    def __init__(self):
        self.__heap = []
        self.__count = 0

    def empty(self) -> bool:
        return self.__count == 0

    def dequeue(self):
        if self.empty():
            raise Exception('empty')
        self.__count -= 1
        return heapq.heappop(self.__heap)

    def enqueue(self, v):
        self.__count += 1
        heapq.heappush(self.__heap, v)

    def __len__(self):
        return self.__count


def cake123(X: int, Y: int, Z: int, K: int, A: list, B: list, C: list)->list:
    ret = [0] * K

    sA = sorted(-a for a in A)
    sB = sorted(-b for b in B)
    sC = sorted(-c for c in C)

    q = PriorityQueue()
    q.enqueue((sA[0] + sB[0] + sC[0], 0, 0, 0))

    used = {}

    k = 0
    while k < K:
        delicious, ai, bi, ci = q.dequeue()
        if -delicious in used and (ai, bi, ci) in used[-delicious]:
            continue

        used.setdefault(-delicious, set())
        used[-delicious].add((ai, bi, ci))

        ret[k] = -delicious
        k += 1

        if ai+1 < X:
            q.enqueue((sA[ai+1] + sB[bi] + sC[ci], ai+1, bi, ci))
        if bi+1 < Y:
            q.enqueue((sA[ai] + sB[bi+1] + sC[ci], ai, bi+1, ci))
        if ci+1 < Z:
            q.enqueue((sA[ai] + sB[bi] + sC[ci+1], ai, bi, ci+1))

    return ret


if __name__ == "__main__":
    X, Y, Z, K = map(int, input().split())
    A = [int(s) for s in input().split()]
    B = [int(s) for s in input().split()]
    C = [int(s) for s in input().split()]
    ans = cake123(X, Y, Z, K, A, B, C)
    for a in ans:
        print(a)

Submission status: Accepted

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

ma,mb,mc = A[0],B[0],C[0]
sA = [a-ma for a in A] + [-10**15]
sB = [b-mb for b in B] + [-10**15]
sC = [c-mc for c in C] + [-10**15]

ia,ib,ic = 0,0,0
while min(10**5,(X)*(Y)*(Z)) > (ia+1)*(ib+1)*(ic+1):
    m = max(sA[ia+1],sB[ib+1],sC[ic+1])
    if ia < (X-1) and sA[ia+1] == m:
        ia = min(ia+1,X-1)
    if ib < (Y-1) and sB[ib+1] == m:
        ib = min(ib+1,Y-1)
    if ic < (Z-1) and sC[ic+1] == m:
        ic = min(ic+1,Z-1)
ans = []
for a in A[:ia+1]:
    for b in B[:ib+1]:
        for c in C[:ic+1]:
            ans.append(a+b+c)
ans.sort(reverse=True)
for out in ans[:K]:
    print(out)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)


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


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(A, B, C, K):
    A.sort(reverse=True)
    B.sort(reverse=True)
    C.sort(reverse=True)

    def s(i, j, k):
        return A[i] + B[j] + C[k]
    used = set()
    
    cand = []
    if 1 < len(A):
        heapq.heappush(cand, (-s(1, 0, 0), (1, 0, 0)))
        used.add((1, 0, 0))
    if 1 < len(B):
        heapq.heappush(cand, (-s(0, 1, 0), (0, 1, 0)))
        used.add((0, 1, 0))
    if 1 < len(C):
        heapq.heappush(cand, (-s(0, 0, 1), (0, 0, 1)))
        used.add((0, 0, 1))
    print(s(0, 0, 0))
    for _ in range(K-1):
        v, i = heapq.heappop(cand)
        print(-v)
        
        ti = (i[0]+1, i[1], i[2])
        if ti[0] < len(A) and ti not in used:
            heapq.heappush(cand, (-s(*ti), ti))
            used.add(ti)
        
        ti = (i[0], i[1]+1, i[2])
        if ti[1] < len(B) and ti not in used:
            heapq.heappush(cand, (-s(*ti), ti))
            used.add(ti)
        
        ti = (i[0], i[1], i[2]+1)
        if ti[2] < len(C) and ti not in used:
            heapq.heappush(cand, (-s(*ti), ti))
            used.add(ti)



def main():
    # for _ in range(1000):
    #     K = 3000
    #     A = [random.randint(1, 10000000000) for _ in range(random.randint(1, 1000))]
    #     B = [random.randint(1, 10000000000) for _ in range(random.randint(1, 1000))]
    #     C = [random.randint(1, 10000000000) for _ in range(random.randint(1, 1000))]
    #     K = min(K, len(A) + len(B) + len(C))
    #     slv(A,B,C,K)
    # N = read_int()
    X, Y, Z, K = read_int_n()
    A = read_int_n()
    B = read_int_n()
    C = read_int_n()
    (slv(A, B, C, K))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import heapq

def solve():
    X=[0]*3
    X[0],X[1],X[2],K=map(int,input().split())
    A=[[] for i in range(3)]
    for i in range(3):
        A[i]=list(map(int,input().split()))
        A[i].sort(reverse=True)
    q = []
    heapq.heappush(q, (-A[0][0]-A[1][0]-A[2][0],0,0,0))
    m = [0 for i in range(3)]
    n = [0 for i in range(3)]
    done = set()
    done.add((0,0,0))
    for k in range(K):
        sc, n[0], n[1], n[2] = heapq.heappop(q)
        print(-sc)
        extend=False
        for i in range(3):
            if m[i] <= n[i] and m[i] < X[i] - 1:
                m[i] += 1
                extend=True
        #print(m,extend)
        if extend:
            for i0 in range(m[0]+1):
                for i1 in range(m[1]+1):
                    for i2 in range(m[2]+1):
                        if (i0,i1,i2) not in done:
                            done.add((i0,i1,i2))
                            heapq.heappush(q, (-A[0][i0]-A[1][i1]-A[2][i2],i0,i1,i2))
        #print(done)

solve()

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()))
inf = 10**18
a.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)
h = [0]*k
heapq.heapify(h)
for i in a:
    for j in b:
        cur = i+j
        t=0
        while t<z and h[0] < cur + c[t]:
            heapq.heappushpop(h, cur + c[t])
            t += 1
r = [heapq.heappop(h) for _ in range(k)]
for _ in range(k):
    print(r.pop())

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

h = []
heappush(h, (0, 0, 0, 0))
val = a[0] + b[0] + c[0]
searched = set()

cnt = 0
while cnt < k:
    cost, ia, ib, ic = heappop(h)
    if (ia, ib, ic) in searched:
        continue
    else:
        searched.add((ia, ib, ic))
        cnt += 1
    print(val - cost)
    if ia < x-1:
        heappush(h, (cost + a[ia] - a[ia+1], ia+1, ib, ic))
    if ib < y-1:
        heappush(h, (cost + b[ib] - b[ib+1], ia, ib+1, ic))
    if ic < z-1:
        heappush(h, (cost + c[ic] - c[ic+1], ia, ib, ic+1))

Submission status: Accepted

Solution code:
import heapq
X, Y, Z, K = map(int, input().split())
A = [int(a) for a in input().split()]
B = [int(b) for b in input().split()]
C = [int(c) for c in input().split()]
A.sort(reverse = True)
A.append(-10**20)
B.sort(reverse = True)
B.append(-10**20)
C.sort(reverse = True)
C.append(-10**20)

Q = []
heapq.heapify(Q)
heapq.heappush(Q, (-(A[0]+B[0]+C[0]), 0, 0, 0))
count = 0
fin = {}
while count < K:
    value, a, b, c = heapq.heappop(Q)
    if (a, b, c) not in fin:
        fin[(a, b, c)] = 1
        print(-value)
        heapq.heappush(Q, (-(A[a+1]+B[b]+C[c]), a+1, b, c))
        heapq.heappush(Q, (-(A[a]+B[b+1]+C[c]), a, b+1, c))
        heapq.heappush(Q, (-(A[a]+B[b]+C[c+1]), a, b, c+1))
        count += 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()))

tem = []

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

tem.sort()
if(x*y > k):
    tem2 = tem[x*y-k-1:]
else:
    tem2 = tem
ans = []
for i in range(len(tem2)):
    for j in range(z):
        ans.append(tem2[i]+c[j])

ans.sort()
dd = len(tem2)*z
for i in list(reversed(range(dd-k,dd))):
    print(ans[i])

Submission status: Accepted

Solution code:
import heapq

class PrioritySet(object):
    def __init__(self):
        self.heap = []
        self.set = set()

    def add(self, pri, d):
        if not d in self.set:
            heapq.heappush(self.heap, (pri, d))
            self.set.add(d)

    def get(self):
        pri, d = heapq.heappop(self.heap)
        self.set.remove(d)
        return (pri, d)

X, Y, Z, K = map(int, input().split())
As = map(int, input().split())
As = sorted(As, reverse=True)
Bs = map(int, input().split())
Bs = sorted(Bs, reverse=True)
Cs = map(int, input().split())
Cs = sorted(Cs, reverse=True)

count = 0
h = PrioritySet()
h.add(-sum([As[0], Bs[0], Cs[0]]), (0, 0, 0))
while True:
    m, ii = h.get()
    ai, bi, ci = ii
    print(-m)
    count += 1
    if count == K:
        break

    if ai + 1 < len(As):
        h.add(-sum([As[ai+1], Bs[bi], Cs[ci]]), (ai+1, bi, ci))
    if bi + 1 < len(Bs):
        h.add(-sum([As[ai], Bs[bi+1], Cs[ci]]), (ai, bi+1, ci))
    if ci + 1 < len(Cs):
        h.add(-sum([As[ai], Bs[bi], Cs[ci+1]]), (ai, bi, ci+1))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from itertools import chain
from functools import reduce
from collections import OrderedDict, Counter, deque
import operator

IA = lambda: [int(x) for x in input().split()]

X,Y,Z,K = IA()
A, B, C = IA(), IA(), IA()
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
S = (A,B,C)

from heapq import *

inf = float('inf')
known = set()
q = []
c = (0,0,0)
v = sum([s[i] for s,i in zip(S, c)])
known.add(c)
heappush(q, (-v, c))
for _ in range(K):
    v, c = heappop(q)
    v = -v
    print(v)
    for i in range(3):
        n = c[i] + 1
        if len(S[i]) > n:
            nc = c[:i] + (n,) + c[i+1:]
            if nc not in known:
                known.add(nc)
                nv = sum([s[i] for s,i in zip(S, nc)])
                heappush(q, (-nv, nc))

Submission status: Accepted

Solution code:
import heapq
X, Y, Z, K = map(int, input().split())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
id = '0' * 9
v = A[0] + B[0] + C[0]
D = {}
D[id] = v
Q = [[-v, id]]
for i in range(K):
  q = heapq.heappop(Q)
  print(-q[0])
  ida = q[1][:3]
  idb = q[1][3:6]
  idc = q[1][6:9]
  if int(ida) < len(A) - 1:
    _ida = int(ida) + 1
    v = A[_ida] + B[int(idb)] + C[int(idc)]
    id = '{:03}'.format(_ida) + idb + idc
    if id not in D:
      D[id] = v
      heapq.heappush(Q, [-v, id])
  if int(idb) < len(B) - 1:
    _idb = int(idb) + 1
    v = A[int(ida)] + B[_idb] + C[int(idc)]
    id = ida + '{:03}'.format(_idb) + idc
    if id not in D:
      D[id] = v
      heapq.heappush(Q, [-v, id])
  if int(idc) < len(C) - 1:
    _idc = int(idc) + 1
    v = A[int(ida)] + B[int(idb)] + C[_idc]
    id = ida + idb + '{:03}'.format(_idc)
    if id not in D:
      D[id] = v
      heapq.heappush(Q, [-v, id])

Submission status: Accepted

Solution code:
import sys
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()))
c.sort(reverse=True)
ab = [0]*(x*y)
l = 0
for i in range(x):
    for j in range(y):
        ab[l] = a[i] + b[j]
        l += 1

ab.sort(reverse=True)
q = 0
i = 0
j = 0
ans = [0]*(k*k)
l = 0
for i in range(min(k,x*y)):
    for j in range(min(k,z)):
        ans[l] = ab[i] + c[j]
        l += 1

ans.sort(reverse=True)

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

Submission status: Accepted

Solution code:
x,y,z,k = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
c = list(map(int,input().split()))
a.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)
cand = []
for xi in range(x):
  if xi+1 > k:
    break
  for yi in range(y):
    if (xi+1)*(yi+1) > k:
        break
    for zi in range(z):
      if (xi+1)*(yi+1)*(zi+1) > k:
        break
      cand.append(a[xi]+b[yi]+c[zi])
cand.sort(reverse=True)
for i in range(k):
  print(cand[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()
B.sort()
C.sort()
from heapq import heappush,heappop
ans=[]
data=[(-A[-1]-B[-1]-C[-1],X-1,Y-1,Z-1)]
visited={(X-1,Y-1,Z-1)}
while len(ans)<K:
    now=heappop(data)
    ans.append(-1*now[0])
    if now[1]>0 and (now[1]-1,now[2],now[3]) not in visited:
        nex=now[0]+A[now[1]]-A[now[1]-1]
        heappush(data,(nex,now[1]-1,now[2],now[3]))
        visited|={(now[1]-1,now[2],now[3])}
    if now[2]>0 and (now[1],now[2]-1,now[3]) not in visited:
        nex=now[0]+B[now[2]]-B[now[2]-1]
        heappush(data,(nex,now[1],now[2]-1,now[3]))
        visited|={(now[1],now[2]-1,now[3])}
    if now[3]>0 and (now[1],now[2],now[3]-1) not in visited:
        nex=now[0]+C[now[3]]-C[now[3]-1]
        heappush(data,(nex,now[1],now[2],now[3]-1))
        visited|={(now[1],now[2],now[3]-1)}
for i in range(K):
    print(ans[i])