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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Author: Kajetan Ramsza
#include "bits/stdc++.h"
using namespace std;

#define rep(i, a, b) for(int i = (a); i < (b); ++i)
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;

template<typename F, typename S> ostream& operator<<(ostream& os, const pair<F, S> &p) { return os<<"("<<p.first<<", "<<p.second<<")"; }
template<typename T> ostream &operator<<(ostream & os, const vector<T> &v) { os << "{"; typename vector< T > :: const_iterator it;
    for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "}"; }

void dbg_out() { cerr<<'\n'; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr<<' '<<H; dbg_out(T...); }

#ifdef DEBUG
#define dbg(...) cerr<<"(" << #__VA_ARGS__ <<"):", dbg_out(__VA_ARGS__)
#else
#define dbg(...) 
#endif

struct Jelly {
	int weight;
	ll cost;
	int color;
};

const int maxm = 7007;
const ll inf = ll(1e18) + 7;

int n, k, m;

Jelly vec[maxm];
array<array<ll,maxm>,maxm> cost;
ll dp[maxm];

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);

	cin>>n>>k>>m;
	rep(i,0,n) cin>>vec[i].color>>vec[i].weight>>vec[i].cost;
	sort(vec, vec+n, [](const auto &a, const auto &b) {
		return a.color < b.color;
	});
	cost[0].fill(inf);
	cost[0][0] = 0;
	int pnt = 0;
	int curr = 0;
	rep(c,1,k+1) {
		cost[c].fill(inf);
		int l = pnt;
		while(pnt < n && vec[pnt].color == c) pnt++;
		int r = pnt;
		rep(x,0,m) rep(i,l,r) {
			int v = (x + vec[i].weight) % m;
			cost[c][v] = min(cost[c][v], cost[c-1][x] + vec[i].cost);
		}
		curr ^= 1;
	}
	cerr<<"tu\n";
	rep(i,1,m) dp[i] = inf; 
	dp[0] = 0;
	rep(r,1,m) {
		if(cost[k][r] == inf) continue;
		int gcd = __gcd(r, m);
		int len = m / gcd;
		rep(start,0,gcd) {
			dbg(start);
			ll mini = inf; 
			rep(i,0,len) {
				int ind = (start + i * r) % m;
				dbg(ind);

				ll c = ll(i) * cost[k][r];
				dp[ind] = min(dp[ind], mini + c);
				mini = min(mini, dp[ind] - c);
			}
			mini = inf;
			ll all = ll(len) * cost[k][r];
			for(int i=len-1;i>=0;i--) {
				int ind = (start + i * r) % m;
				dbg(i, ind, mini);

				ll c = ll(i) * cost[k][r];
				dp[ind] = min(dp[ind], all + mini + c);
				mini = min(mini, dp[ind] - c);
			}
		}

		rep(i,0,m) dbg(i, dp[i]);
	}
	rep(i,0,m) {
		cout<<(dp[i] == inf ? -1 : dp[i])<<'\n';
	}
}