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
#include<bits/stdc++.h>
using namespace std;

struct zel {
    int kol, mas, cen;
    zel() : kol(0), mas(0), cen(0) {}
    zel(int _kol, int _mas, int _cen) : kol(_kol), mas(_mas), cen(_cen) {}
};

const long long inf = 1e15;

void solve() {
    int n, k, m; cin >> n >> k >> m;
    vector<zel> v(n);
    for (int i = 0; i < n; i++) {
        cin >> v[i].kol >> v[i].mas >> v[i].cen;
    }
    sort(v.begin(), v.end(), [](const zel &a, const zel &b) {
        return a.kol < b.kol;
    });

    //cout << "\n";
    //for(auto &x : v) cout << x.kol << " " << x.mas << " " << x.cen << "\n";
    //cout << "\n";

    vector<vector<long long>> dp(k + 1, vector<long long>(m, inf));
    dp[0][0] = 0;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            dp[v[i].kol][j] = min(dp[v[i].kol][j], 
                                  dp[v[i].kol - 1][(j - v[i].mas + m) % m] + v[i].cen);
        }
    }

    //for(auto &x : dp) {
    //    for(auto &y : x) cout << y << " ";
    //    cout << "\n";
    //}
    //cout << "\n";

    vector<pair<long long, long long>> moves;
    vector<long long> ans(m, -1); 
    priority_queue<pair<long long, long long>, vector<pair<long long, long long>>, greater<>> q;
    for(int i = 0; i < m; i++) {
        if(dp[k][i] != inf) {
            moves.push_back({dp[k][i], i});
            q.push({dp[k][i], i});
            ans[i] = dp[k][i];
        }
    }

    //for(auto &x : moves) {
    //    cout << x.first << " " << x.second << "\n";
    //}
    //cout << "\n";
    ans[0LL] = 0LL;
    while(!q.empty()) {
        long long cost = q.top().first;
        long long pos = q.top().second;
        q.pop();

        //cout << "\n" << cost << " " << pos << "\n";

        if(ans[pos] != cost) continue;
        //ans[pos] = cost;
        for(auto &x : moves) {
            //cout  << (pos + x.second) % m << " " << cost + x.first << "\n";
            long long new_cost = cost + x.first;
            long long new_pos = (pos + x.second) % m;
            if(ans[new_pos] == -1 || new_cost < ans[new_pos]) {
                if(new_pos == 0) cout << ans[new_pos] << " " << new_cost << "\n\n";
                ans[new_pos] = new_cost;
                q.push({new_cost, new_pos});
            }
        }
    }
    //cout << "\n";
    for(int i = 0; i < m; i++) cout << ans[i] << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    solve();
    return 0;
}