1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from functools import cache

n, k, mod = map(int, input().split()) # n, colors, mod

colors = {}
for c in range(1, k+1):
    colors[c] = [(0, float('inf'))] # add a dummy item to avoid index errors
for i in range(n):
    col, m, cost = map(int, input().split()) # color, mass, cost
    colors[col].append((m, cost))

@cache
def get(c, r, num): # color, remaining mass, number of items
    if r == 0 and num == 0: return 0
    if num == 0: return float('inf')

    return min(get(c, (r - m) % mod, num - 1) + cost for m, cost in colors[c]) 

@cache
def get_total(c, r, num): # color, remaining mass, number of items
    if r == 0 and c == k+1: return 0
    if c == k+1: return float('inf')

    return min(get_total(c+1, (r - r2) % mod, num) + get(c, r2, num) for r2 in range(mod))

for r in range(mod):
    best = float('inf') 
    for num in range(mod+1):
        best = min(best, get_total(1, r, num))
    print(best if best != float('inf') else -1)