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

l = len(a) * len(b)
s = [0] * l
ans = [0] * (3000 * len(c))

i = 0
for A in a:
    for B in b:
        s[i] = A + B
        i += 1
s.sort(reverse=True)

i = 0
for S in s[:3000]:
    for C in c:
        ans[i] = C + S
        i += 1
ans.sort(reverse=True)

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

Submission status: Accepted

Solution code:
def get_unique_list(seq):
    seen = []
    return [x for x in seq if x not in seen and not seen.append(x)]


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)

abc = [[0,0,0,A[0]+B[0]+C[0]]]
list_abc = [[0,0,0]]
#next_abc = [[1,0,0],[0,1,0],[0,0,1]]
#print(A[abc[0][0]]+B[abc[0][1]]+C[abc[0][2]])

for i in range(K):
    max_v = 0
    for j in range(len(abc)):
        if abc[j][3] > max_v:
            max_v = abc[j][3]
            temp_j = j
            
    max_abc = abc.pop(temp_j)
    #print(max_abc)
    #print(A[max_abc[0]]+B[max_abc[1]]+C[max_abc[2]])
    print(max_v)
    
    if max_abc[0]<X-1:
        if not([max_abc[0]+1, max_abc[1], max_abc[2]] in list_abc):
            abc.append([max_abc[0]+1,max_abc[1],max_abc[2],A[max_abc[0]+1]+B[max_abc[1]]+C[max_abc[2]]])
            list_abc.append([max_abc[0]+1, max_abc[1], max_abc[2]])
    if max_abc[1]<Y-1:
        if not([max_abc[0], max_abc[1]+1, max_abc[2]] in list_abc):
            abc.append([max_abc[0],max_abc[1]+1,max_abc[2],A[max_abc[0]]+B[max_abc[1]+1]+C[max_abc[2]]])
            list_abc.append([max_abc[0], max_abc[1]+1, max_abc[2]])
    if max_abc[2]<Z-1:
        if not([max_abc[0], max_abc[1], max_abc[2]+1] in list_abc):
            abc.append([max_abc[0],max_abc[1],max_abc[2]+1,A[max_abc[0]]+B[max_abc[1]]+C[max_abc[2]+1]])
            list_abc.append([max_abc[0], max_abc[1], max_abc[2]+1])
    #abc = get_unique_list(abc)
    #print(abc)

Submission status: Accepted

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

def solve():
    """ TLE """
    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)

    ans = []

    for x in range(X):
        for y in range(Y):
            ab = A[x] + B[y]
            for z in range(Z):
                if (x+1)*(y+1)*(z+1) > K:
                    break

                ans.append(ab + C[z])

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


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    a = IR(5)
    k = II()
    if max(a) - min(a) > k:
        print(":(")
    else:
        print("Yay!")
    return

#B
def B():
    a = IR(5)
    b = a[0]
    ans = 0
    for a_ in a:
        if a_ % 10 != 0:
            if b % 10> a_ % 10:
                b = a_
    flg = 0
    for a_ in a:
        if a_ != b or flg:
            ans += math.ceil(a_ / 10) * 10
        else:
            ans += b
            flg = 1
    print(ans)
            
    
    return

#C
def C():
    n = II()
    ai = IR(5)
    print(math.ceil(n / min(ai)) + 4)
        
        
    return

#D
def D():
    x, y, z, K = LI()
    a = LI()
    a.sort(reverse=True)
    b = LI()
    b.sort(reverse = True)
    c = LI()
    c.sort(reverse=True)
    ab = []
    for a_ in a:
        for b_ in b:
            ab.append(a_ + b_)
    ab.sort(reverse = True)
    ab = ab[:K]
    ans = []
    for ab_ in ab:
        for c_ in c:
            ans.append(ab_ + c_)
    ans.sort(reverse = True)
    for k in range(K):
        print(ans[k])



        
                    

    return

#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Accepted

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, 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 [int(x) for x in sys.stdin.readline().split()]
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 pf(s): return print(s, flush=True)

"""
最大、最大2なら、あとはなにかけあわせても最大しかない
ABCの最大2個なので、プラス残りのlen()を足す。
もし超えたら、その組み合わせで順番にもとめていく
"""
X, Y, Z, K = LI()
A = sorted(LI(), reverse=True)
B = sorted(LI(), reverse=True)
C = sorted(LI(), reverse=True)

e = []
for a in A:
    for b in B:
        e.append(a+b)
e = sorted(e, reverse=True)[:K]
results = []
for item in e:
    for c in C:
        results.append(item+c)

for i in sorted(results, reverse=True)[:K]:
    print(i)

#  #  ABC = A+B+C
#  #  ABC = sorted(ABC, reverse=True)
#  #  #  print(ABC)
#  INF = 10**18
#  a,b,c = [INF],[INF],[INF]
#  #  abc = 0
#  count = 0
#  while a[-1] > B[0] or a[-1] > C[0] or len(a) <= min(50, X):
#      a.append(A[count])
#      count += 1
#      if count >= len(A):
#          break


#  count = 0
#  while b[-1] > A[0] or b[-1] > C[0] or len(b) <= min(50, Y):
#      b.append(B[count])
#      count += 1
#      if count >= len(B):
#          break

#  count = 0
#  while c[-1] > B[0] or c[-1] > A[0] or len(c) <= min(50, Z):
#      c.append(C[count])
#      count += 1
#      if count >= len(C):
#          break
#  a = a[1:]
#  b = b[1:]
#  c = c[1:]

#  #  while a[-1] > b[0] and a[-1] > c[0] and b[-1] > a[0] and b[-1] > c[0] and c[-1] > a[0] and c[-1] > b[0]:

#  #  while not(len(a) >= min(100, X) and len(b) >= min(100, Y) and len(c) >= min(100, Z)):
#  #      if A:
#  #          if ABC[abc]in A:
#  #              a.append(ABC[abc])
#  #              A.remove(ABC[abc])
#  #      if B:
#  #          if ABC[abc]in B:
#  #              b.append(ABC[abc])
#  #              B.remove(ABC[abc])
#  #      if C:
#  #          if ABC[abc]in C:
#  #              c.append(ABC[abc])
#  #              C.remove(ABC[abc])
#  #      abc+=1
#  #  #  for abc in range(min(200, X+Y+Z)):

#  #  #      if ABC[abc]in A:
#  #  #          a.append(ABC[abc])
#  #  #          A.remove(ABC[abc])
#  #  #      if ABC[abc]in B:
#  #  #          b.append(ABC[abc])
#  #  #          B.remove(ABC[abc])
#  #  #      if ABC[abc]in C:
#  #  #          c.append(ABC[abc])
#  #  #          C.remove(ABC[abc])
#  #  #  print(a,b,c)

#  points = []
#  for i in a:
#      for j in b:
#          for k in c:
#              points.append(i+j+k)
#  #  print(points)


#  #  #  A = A[:min(250, X)]
#  #  #  B = B[:min(250, Y)]
#  #  #  C = C[:min(250, Z)]
#  #  #  # Aの中で最大の数字足すBの最大、Cの最大は全体の中で最大
#  #  #  # 3000個大きい順に求めれば良い

#  #  #  # iが決まれば、j,kのおおきさは分かる
#  #  #  BC = []
#  #  #  # 1000*1000 で10**6の計算量
#  #  #  #  for j in range(len(B)):
#  #  #  #      for k in range(len(C)):
#  #  #  #          BC.append(B[j] + C[k])

#  #  #  points = []
#  #  #  # 10**3 と 10** 6
#  #  #  #  for i in range(len(A)):
#  #  #  #      points += [bc + A[i] for bc in BC]
#  #  #  for i in range(len(A)):
#  #  #      #  for bc in BC:
#  #  #      #      points.append(A[i]+bc)
#  #  #      for j in range(len(B)):
#  #  #          for k in range(len(C)):
#  #  #              points.append(A[i] + B[j] + C[k])
#  for i in sorted(points, reverse=True)[:K]:
#      print(i)

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

heap = []
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)

seen = set((0, 0, 0))

heap = [[-(A[0]+B[0]+C[0]), 0, 0, 0]]
for _ in range(K):
    v, i, j, k = heapq.heappop(heap)
    print(-v)
    if i+1 < len(A) and (i+1, j, k) not in seen:
        seen.add((i+1, j, k))
        heapq.heappush(heap, [-(A[i+1]+B[j]+C[k]), i+1, j, k])
    if j+1 < len(B) and (i, j+1, k) not in seen:
        seen.add((i, j+1, k))
        heapq.heappush(heap, [-(A[i]+B[j+1]+C[k]), i, j+1, k])
    if k+1 < len(C) and (i, j, k+1) not in seen:
        seen.add((i, j, k+1))
        heapq.heappush(heap, [-(A[i]+B[j]+C[k+1]), i, j, k+1])

Submission status: Accepted

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

from heapq import heappush, heappop
def io_generator():
	return input()

#+++++++++++++++++++
	
class Foo(object):
	def __init__(self, value, state):
		self.state = state
		self.value = value

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

def get_c(aa,ab,ac, amm):
	if ac < amm[2]-1:
		ret=[[aa,ab,ac+1]]
	else:
		ret=[]
		
	if ab<amm[1]-1:# and ab >= ac:
		ret.append([aa,ab+1,ac])
	
	if aa<amm[0]-1:# and aa >= ab and aa >= ac:
		ret.append([aa+1,ab,ac])
	return ret
	
def gv(al,bl,cl,s):
	return al[s[0]]+bl[s[1]]+cl[s[2]]
	
def lss(l):
	return '_'.join([str(i) for i in l])
	
def main(io):
	x,y,z,k=map(int, io().split())
	ml=[x,y,z]
	al =list(map(int, io().split()))
	al.sort(reverse=True)
	bl =list(map(int, io().split()))
	bl.sort(reverse=True)
	cl =list(map(int, io().split()))
	cl.sort(reverse=True)
	init=[0,0,0]
	ggv=lambda l : gv(al,bl,cl,l)
	
	qq = []
	heappush(qq,Foo(ggv(init), init))
	
	ol=set()
	ol.add(lss(init))
	
	for _ in range(k):
		ff=heappop(qq)
		vv=ff.value
		cs=ff.state
		nc=get_c(cs[0],cs[1],cs[2],ml)
		print(vv)
		for ns in nc:
			if lss(ns) in ol:
				continue
			else:
				heappush(qq, Foo(ggv(ns), ns))
				ol.add(lss(ns))
	return 1

#++++++++++++++++++++

if __name__ == "__main__":
	io= lambda : io_generator()
	#print (main(io))
	main(io)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from heapq import merge
from bisect import bisect
def inpl(): return list(map(int, input().split()))

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

AB = [-1] * K
for a in A[::-1]:
    if AB[0] >= B[-1] + a:
        break
    tmp = [a + b for b in B[bisect(B, AB[0]-a):]][-K:]
    AB = list(merge(tmp, AB))[-K:]

ans = [-1] * K

for c in C:
    if ans[0] >= AB[-1] + c:
        break
    tmp = [ab + c for ab in AB[bisect(AB, ans[0]-c):]][-K:]
    ans = list(merge(ans, tmp))[-K:]

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

Submission status: Accepted

Solution code:
import heapq
X, Y, Z, K = map(int, input().split())
candy = [[],[],[]]
for i in range(3):
    temp = list(map(int, input().split()))
    candy[i] = temp

for i in range(3):
    candy[i] = sorted(candy[i], reverse=True)
i, j, k = 0, 0, 0
heap = [(-(candy[0][i] + candy[1][j] + candy[2][k]), i, j, k)]
cnt = 0
visit = {(i, j, k)}
while cnt < K:
    s, ii, jj, kk = heapq.heappop(heap)
    print(-s)
    cnt += 1
    if ii < len(candy[0]) - 1 and (ii+1, jj, kk) not in visit:
        heapq.heappush(heap, (-(candy[0][ii + 1] + candy[1][jj] + candy[2][kk]), ii + 1, jj, kk))
        visit.add((ii+1, jj, kk))
    if jj < len(candy[1]) - 1 and (ii, jj+1, kk) not in visit:
        heapq.heappush(heap, (-(candy[0][ii] + candy[1][jj + 1] + candy[2][kk]), ii, jj + 1, kk))
        visit.add((ii, jj+1, kk))
    if kk < len(candy[2]) - 1 and (ii, jj, kk+1) not in visit:
        heapq.heappush(heap, (-(candy[0][ii] + candy[1][jj] + candy[2][kk + 1]), ii, jj, kk + 1))
        visit.add((ii, jj, kk+1))

Submission status: Accepted

Solution code:
def ii2ss(n):
    ss = []
    for i in range(n):
        ss.append(input())
    return ss

def sp2nn(sp, sep=' '):
    return [int(s) for s in sp.split(sep)]

def ss2nn(ss):
    return [int(s) for s in list(ss)]

def tk(i, j, k):
    return '%d %d %d' % (i, j, k)

def tkr(key):
    return sp2nn(key)

def main(ss):
    X, Y, Z, K = sp2nn(ss[0])
    aa = sp2nn(ss[1])
    bb = sp2nn(ss[2])
    cc = sp2nn(ss[3])
    aa.sort()
    aa.reverse()
    bb.sort()
    bb.reverse()
    cc.sort()
    cc.reverse()
    
    d = {}
    st = set()
    key = tk(0, 0, 0)
    st.add(key)
    d[key] = aa[0] + bb[0] + cc[0]
    for _ in range(K):
        vmax = -1
        vk = ''
        for k, v in d.items():
            if vmax < v:
                vmax = v
                vk = k
        print(vmax)
        d.pop(vk)
        st.add(vk)
        i, j, k = tkr(vk)
        if i + 1 < len(aa):
            key = tk(i+1, j, k)
            if key not in st:
                d[key] = aa[i+1] + bb[j] + cc[k]
        if j + 1 < len(bb):
            key = tk(i, j+1, k)
            if key not in st:
                d[key] = aa[i] + bb[j+1] + cc[k]
        if k + 1 < len(cc):
            key = tk(i, j, k+1)
            if key not in st:
                d[key] = aa[i] + bb[j] + cc[k+1]
        
main(ii2ss(4))

Submission status: Accepted

Solution code:
import bisect

X, Y, Z, K = list(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)

x_i = 0
y_i = 0
z_i = 0

def cand_index(x_i, y_i, z_i):
    cs = [(x_i+1, y_i, z_i)] if x_i+1 < X else []
    cs += [(x_i, y_i+1, z_i)] if y_i+1 < Y else []
    cs += [(x_i, y_i, z_i+1)] if z_i+1 < Z else []
    return set(cs)

num_xyz = [[x[0]+ y[0]+ z[0], (0, 0, 0)]]
used = set()
ans = []
num = 0
for _ in range(K):
    num, xyz = num_xyz.pop(0)
    ans.append(num)

    new_cand = cand_index(*xyz)
    cand = new_cand - used
    used |= new_cand

    num_xyz += [[x[xyz[0]] + y[xyz[1]] + z[xyz[2]], xyz] for xyz in cand]
    num_xyz = sorted(num_xyz, key=lambda x: x[0], reverse=True)

for a in ans:
    print(a)

Submission status: Accepted

Solution code:
import queue
import heapq

class point:
    def __init__(self):
        self.num = 0
        self.line = [0 for _ in range(3)]

    def __lt__(self, other):
        return self.num > other.num


ABC = list(map(int, input().split()))
K = ABC[-1]
ABC.pop()
ABCL = [list(map(int, input().split())) for _ in range(3)]
for i in range(3):
    ABCL[i] = sorted(ABCL[i])
    ABCL[i] = list(reversed(ABCL[i]))
s = set()
p = point()
p.num = sum([ABCL[i][0] for i in range(3)])
s.add(tuple(p.line))
que = []
heapq.heappush(que, p)
for _ in range(K):
    c = heapq.heappop(que)
    print(c.num)
    for i in range(3):
        d = point()
        d.num = c.num
        for j in range(3):
            d.line[j] = c.line[j]
        if d.line[i] + 1 == ABC[i]:
            continue
        d.num -= ABCL[i][d.line[i]]
        d.line[i] += 1
        d.num += ABCL[i][d.line[i]]
        if tuple(d.line) in s:
            continue
        s.add(tuple(d.line))
        heapq.heappush(que, d)

Submission status: Accepted

Solution code:
from collections import defaultdict
d = defaultdict(list)
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)

AN = min(K+1,len(A))
BN = min(K+1,len(B))
CN = min(K+1,len(C))
AD =  [A[i]-A[i+1] for i in range(AN-1)]
BD =  [B[i]-B[i+1] for i in range(BN-1)]
CD =  [C[i]-C[i+1] for i in range(CN-1)]

d[0].append([0,0,0])

m = A[0]+B[0]+C[0]
cnt = 0
off = []
while(True):
	if not d:
		exit()
	r = min(d)
	for ind in d[r][:]:
		off.append(ind)
		print(m-r)
		cnt = cnt + 1
		if cnt >= K:
			exit()
		ia,ib,ic = ind
		if ia < AN-1:
			add = [ia+1,ib,ic]
			if not add in off:
				off.append(add)
				d[r+AD[ia]].append(add)
		if ib < BN-1:
			add = [ia,ib+1,ic]
			if not add in off:
				off.append(add)
				d[r+BD[ib]].append(add)
		if ic < CN-1:
			add = [ia,ib,ic+1]
			if not add in off:
				off.append(add)
				d[r+CD[ic]].append(add)
		d[r].remove(ind)
	if not d[r]:
		del d[r]

Submission status: Accepted

Solution code:
from collections import defaultdict
inpl = lambda: list(map(int,input().split()))

X, Y, Z, K = inpl()
A = [ sorted(inpl(), key=lambda x: -x) for _ in range(3) ]
N = [X, Y, Z]

mem = defaultdict(int)
ans = sum([A[i][0] for i in range(3)])
mem[(0,0,0)] = 1
cand = [(ans,0,0,0)]

for i in range(K):
    cand.sort()
    c = cand[-1]
    print(c[0])
    n = [c[1],c[2],c[3]]
    cand.pop(-1)
    
    for p in range(3):
        if n[p] < N[p]-1:
            n[p] += 1
            if mem[(n[0],n[1],n[2])] == 0:
                mem[(n[0],n[1],n[2])] = 1
                cand.append((sum([A[j][n[j]] for j in range(3)]),n[0],n[1],n[2]))
            n[p] -= 1

Submission status: Accepted

Solution code:
import numpy as np


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

As = sorted(As, reverse=True)
Bs = sorted(Bs, reverse=True)
Cs = sorted(Cs, reverse=True)

idx_1, idx_2, idx_3 = 0, 0, 0
INF = 10 ** 11
answers = list()

candidates = [(idx_1, idx_2, idx_3)]
end_cands = set()
values = [As[idx_1] + Bs[idx_2] + Cs[idx_3]]
for i in range(k):
    while True:
        ans_idx = np.argmax(values)
        cand = candidates.pop(ans_idx)
        ans = values.pop(ans_idx)
        if cand not in end_cands:
            break
    idx_1, idx_2, idx_3 = cand
    answers.append(ans)
    end_cands.add(cand)
    # print(cand, ans)

    if idx_1 + 1 != x:
        candidates.append((idx_1 + 1, idx_2, idx_3))
        values.append(As[idx_1 + 1] + Bs[idx_2] + Cs[idx_3])
    if idx_2 + 1 != y:
        candidates.append((idx_1, idx_2 + 1, idx_3))
        values.append(As[idx_1] + Bs[idx_2 + 1] + Cs[idx_3])
    if idx_3 + 1 != z:
        candidates.append((idx_1, idx_2, idx_3 + 1))
        values.append(As[idx_1] + Bs[idx_2] + Cs[idx_3 + 1])

for ans in answers:
    print(ans)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop

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()]
A.sort(reverse=True)
B.sort(reverse=True)
C.sort(reverse=True)
h = []

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


def inv(v):
    return maxv - v


pushed = [[[] for _ in range(Y)] for _ in range(X)]
heappush(h, (0, 0, 0, 0))
for _ in range(K):
    invv, i, j, k = heappop(h)
    print(inv(invv))
    if i + 1 < X and k not in pushed[i + 1][j]:
        heappush(h, (inv(A[i + 1] + B[j] + C[k]), i + 1, j, k))
        pushed[i + 1][j].append(k)
    if j + 1 < Y and k not in pushed[i][j + 1]:
        heappush(h, (inv(A[i] + B[j + 1] + C[k]), i, j + 1, k))
        pushed[i][j + 1].append(k)
    if k + 1 < Z and k + 1 not in pushed[i][j]:
        heappush(h, (inv(A[i] + B[j] + C[k + 1]), i, j, k + 1))
        pushed[i][j].append(k + 1)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

from collections import deque, defaultdict
import bisect

X, Y, Z, K = map(int, input().rstrip().split(' '))
A = sorted(list(map(int, input().rstrip().split(' '))))[::-1]
B = sorted(list(map(int, input().rstrip().split(' '))))[::-1]
C = sorted(list(map(int, input().rstrip().split(' '))))[::-1]

ai = 0
bi = 0
ci = 0


diff = [1, 0, -1]
memo = set()
memo.add('000000000000')
    
d = defaultdict(lambda: [])
current_total = A[ai] + B[bi] + C[ci]
totals = [current_total]
d[current_total].append([ai, bi, ci])
current_total_index = 0
count = 0
while True:
    current_total = totals[-(current_total_index+1)]

    for candidate in d[current_total]:
        count += 1
        ai, bi, ci = candidate
        print(current_total)
        if count >= K:
            break
        for i in diff:
            for j in diff:
                for k in diff:
                    if (ai + i) < 0 or (ai + i) >= len(A) or (bi + j) < 0 or (bi + j) >= len(B) or (ci + k) < 0 or (ci + k) >= len(C):
                        continue
                    
                    before_len_memo = len(memo)
                    memo.add('{:04d}{:04d}{:04d}'.format(ai + i, bi + j, ci + k))
                    if before_len_memo != len(memo):
                        total = A[ai+i] + B[bi+j] + C[ci+k]
                        
                        if len(d[total]) == 0:
                            bisect.insort_right(totals, total)
                        
                        d[total].append([ai+i, bi+j, ci+k])
                    
        
    if count >= K:
        break
        
    current_total_index += 1

Submission status: Accepted

Solution code:
import heapq

x, y, z, k = map(int, input().split())
ali = list(reversed(sorted(map(int, input().split()))))
bli = list(reversed(sorted(map(int, input().split()))))
cli = list(reversed(sorted(map(int, input().split()))))

done = {}
count = 0

heap = []


def main(a, b, c):
    global count
    if '{}'.format((a, b, c)) in done:
        return
    done['{}'.format((a, b, c))] = True
    count += 1
    print(ali[a] + bli[b] + cli[c])
    if a + 1 < x:
        heapq.heappush(heap, (-(ali[a + 1] + bli[b] + cli[c]), a + 1, b, c))
    if b + 1 < y:
        heapq.heappush(heap, (-(ali[a] + bli[b + 1] + cli[c]), a, b + 1, c))
    if c + 1 < z:
        heapq.heappush(heap, (-(ali[a] + bli[b] + cli[c + 1]), a, b, c + 1))


main(0, 0, 0)
while count < k:
    s, a, b, c = heapq.heappop(heap)
    main(a, b, c)

Submission status: Accepted

Solution code:
import heapq as hp
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 = [0]*k
hp.heapify(h)
for i in a:
  for j in b:
    cur = i+j
    t = 0
    while t < z and h[0] < cur+c[t]:
      hp.heappushpop(h, cur + c[t])
      t += 1
r = [hp.heappop(h) for _ in range(k)]
for _ in range(k):
  print(r.pop())

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 = []
    heapq.heappush(cand, (-s(0, 0, 0), (0, 0, 0)))
    for _ in range(K):
        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:
read = input
def read_numbers():
    a = read().split(' ')
    a = list(map(int, a))
    return a
[x,y,z,K] = read_numbers()
memo = [[set() for i in range(y)]for i in range(x)]
X = read_numbers()
Y = read_numbers()
Z = read_numbers()
X.sort()
X.reverse()
Y.sort()
Y.reverse()
Z.sort()
Z.reverse()
import queue
def cal(px, py,pz):
    return X[px]+Y[py]+Z[pz]
memo[0][0].add(0)
cnt = 0
pq = queue.PriorityQueue()
# print(X,Y,Z)
pq.put((-cal(0,0,0) ,0,0,0))
while(cnt < K):
#     print(cnt)
    cost , px, py, pz = pq.get(timeout=1)
#     print(cost, px, py,pz)
    for i in range(px-1, px + 2):
        for j in range(py-1, py + 2):
            for k in range(pz-1, pz + 2):
                if (i >= 0 and i < x and 
                    j >= 0 and j < y and 
                    k >=0 and k < z and
                    k not in memo[i][j]
                   ):
                    memo[i][j].add(k)
                    pq.put((-cal(i,j,k),i,j,k))
    print(-cost)
    cnt = cnt + 1

Submission status: Accepted

Solution code:
import numpy as np
import itertools
x,y,z,k = [int(_) for _ in input().split(" ")]
A = np.array([int(_) for _ in input().split(" ")])
B = np.array([int(_) for _ in input().split(" ")])                                                  
C = np.sort([int(_) for _ in input().split(" ")])

AB = A.reshape(1,x) + B.reshape(y,1)
sorted_ab  = np.sort(AB.flatten())[::-1][:k]
abc = np.expand_dims(sorted_ab,0) + C.reshape(z,1)
sorted_abc = np.sort(abc.flatten())[::-1]
for i in range(k):
    print(sorted_abc[i])

Submission status: Accepted

Solution code:
#!/usr/bin/python
import sys
import heapq
R=lambda:map(int,sys.stdin.readline().split())
xa,xb,xc,k=R()
a=sorted(R())
b=sorted(R())
c=sorted(R())
h=set()
q=[[-(a[-1]+b[-1]+c[-1]),xa-1,xb-1,xc-1]]
for _ in range(k):
	x,ya,yb,yc=heapq.heappop(q)
	print(-x)
	if ya>0 and (ya-1,yb,yc) not in h:
		h.add((ya-1,yb,yc))
		heapq.heappush(q,[x+a[ya]-a[ya-1],ya-1,yb,yc])
	if yb>0 and (ya,yb-1,yc) not in h:
		h.add((ya,yb-1,yc))
		heapq.heappush(q,[x+b[yb]-b[yb-1],ya,yb-1,yc])
	if yc>0 and (ya,yb,yc-1) not in h:
		h.add((ya,yb,yc-1))
		heapq.heappush(q,[x+c[yc]-c[yc-1],ya,yb,yc-1])

Submission status: Accepted

Solution code:
import numpy as np
import math

xyzk=input().split()
X=int(xyzk[0])
Y=int(xyzk[1])
Z=int(xyzk[2])
K=int(xyzk[3])
A = list(map(int,input().split()))
B = list(map(int,input().split()))
C = list(map(int,input().split()))
xy_size = min(3000,X*Y)
xy = np.zeros((X,Y))
for i in range(X):
    xy[i,:] += A[i]
for i in range(Y):
    xy[:,i] += B[i]
xy = np.sort(xy.reshape(-1))[::-1][:xy_size]
#print(xy)

xyz = np.zeros((xy_size,Z))
for i in range(xy_size):
    xyz[i,:] += xy[i]
for i in range(Z):
    xyz[:,i] += C[i]

xyz = np.sort(xyz.reshape(-1))[::-1][:K]
#print(xyz)
for num in xyz:
    print(int(num))