#include <bits/stdc++.h> using namespace std; int n, k, m; vector <pair <int, long long>> kol[15005]; long long dp[3][15005]; bool xd; vector <pair <int, long long>> sas; priority_queue <pair <long long, int>> pq; long long dist[15005]; bool vis[15005]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int a, b, c; cin >> n >> k >> m; for (int i = 0; i < n; ++i) { cin >> a >> b >> c; kol[a].push_back({b, c}); } for (int j = 1; j < m; ++j) { dp[0][j] = 1e17; } for (int i = 1; i <= k; ++i) { if (kol[i].size() == 0) { xd = true; break; } for (int j = 0; j < m; ++j) { dp[i&1][j] = 1e17; } for (int j = 0; j < m; ++j) { for (pair <int, long long> h : kol[i]) { dp[i&1][(j + h.first)%m] = min(dp[i&1][(j + h.first)%m], dp[(i-1)&1][j] + h.second); } } } if (xd) { cout << 0 << "\n"; for (int i = 1; i < m; ++i) { cout << "-1\n"; } return 0; } for (int i = 0; i < m; ++i) { dist[i] = 1e17; if (dp[k&1][i] < 1e17) { sas.push_back({i, dp[k&1][i]}); } } pq.push({0, 0}); while (!pq.empty()) { long long val = -pq.top().first, idx = pq.top().second; pq.pop(); if (vis[idx]) { continue; } dist[idx] = val; vis[idx] = true; for (pair <int, long long> i : sas) { if (!vis[(i.first + idx)%m]) pq.push({-val - i.second, (i.first + idx)%m}); } } for (int i = 0; i < m; ++i) { if (dist[i] < 1e17) { cout << dist[i] << "\n"; } else { cout << "-1\n"; } } }
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 | #include <bits/stdc++.h> using namespace std; int n, k, m; vector <pair <int, long long>> kol[15005]; long long dp[3][15005]; bool xd; vector <pair <int, long long>> sas; priority_queue <pair <long long, int>> pq; long long dist[15005]; bool vis[15005]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int a, b, c; cin >> n >> k >> m; for (int i = 0; i < n; ++i) { cin >> a >> b >> c; kol[a].push_back({b, c}); } for (int j = 1; j < m; ++j) { dp[0][j] = 1e17; } for (int i = 1; i <= k; ++i) { if (kol[i].size() == 0) { xd = true; break; } for (int j = 0; j < m; ++j) { dp[i&1][j] = 1e17; } for (int j = 0; j < m; ++j) { for (pair <int, long long> h : kol[i]) { dp[i&1][(j + h.first)%m] = min(dp[i&1][(j + h.first)%m], dp[(i-1)&1][j] + h.second); } } } if (xd) { cout << 0 << "\n"; for (int i = 1; i < m; ++i) { cout << "-1\n"; } return 0; } for (int i = 0; i < m; ++i) { dist[i] = 1e17; if (dp[k&1][i] < 1e17) { sas.push_back({i, dp[k&1][i]}); } } pq.push({0, 0}); while (!pq.empty()) { long long val = -pq.top().first, idx = pq.top().second; pq.pop(); if (vis[idx]) { continue; } dist[idx] = val; vis[idx] = true; for (pair <int, long long> i : sas) { if (!vis[(i.first + idx)%m]) pq.push({-val - i.second, (i.first + idx)%m}); } } for (int i = 0; i < m; ++i) { if (dist[i] < 1e17) { cout << dist[i] << "\n"; } else { cout << "-1\n"; } } } |