#include <bits/stdc++.h> using namespace std; typedef long long ll; constexpr ll MAX = 1e18; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, k, m; cin >> n >> k >> m; vector<unordered_map<int, ll>> gellies(k); for(int i = 0; i < n; i++) { ll ki, mi, ci; cin >> ki >> mi >> ci; ki--; mi %= m; if(gellies[ki].find(mi) == gellies[ki].end()) gellies[ki][mi] = ci; else gellies[ki][mi] = min(ci, gellies[ki][mi]); } vector<ll> one(m, MAX); one[0] = 0; for(int i = 0; i < k; i++) { vector<ll> tmp(m, MAX); for(int j = 0; j < m; j++) { for(auto it2 : gellies[i]) { tmp[(j + it2.first) % m] = min(tmp[(j + it2.first) % m], one[j] + it2.second); } } one = tmp; } vector<vector<ll>> graph(m, vector<ll>(m, MAX)); for(int i = 0; i < m; i++) { for(int j = 0; j < m; j++) { graph[i][(i + j) % m] = one[j]; } } vector<ll> dist(m, MAX); vector<bool> visited(m, false); dist[0] = 0; for(int c = 0; c < m; c++) { int idx = -1; for(int i = 0; i < m; i++) { if(!visited[i]) { if(idx == -1) idx = i; else if(dist[i] < dist[idx]) idx = i; } } visited[idx] = true; for(int i = 0; i < m; i++) { if(!visited[i]) dist[i] = min(dist[i], dist[idx] + graph[idx][i]); } } for(int i = 0; i < m; i++) { if(dist[i] == MAX) cout << "-1\n"; else cout << dist[i] << '\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 | #include <bits/stdc++.h> using namespace std; typedef long long ll; constexpr ll MAX = 1e18; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, k, m; cin >> n >> k >> m; vector<unordered_map<int, ll>> gellies(k); for(int i = 0; i < n; i++) { ll ki, mi, ci; cin >> ki >> mi >> ci; ki--; mi %= m; if(gellies[ki].find(mi) == gellies[ki].end()) gellies[ki][mi] = ci; else gellies[ki][mi] = min(ci, gellies[ki][mi]); } vector<ll> one(m, MAX); one[0] = 0; for(int i = 0; i < k; i++) { vector<ll> tmp(m, MAX); for(int j = 0; j < m; j++) { for(auto it2 : gellies[i]) { tmp[(j + it2.first) % m] = min(tmp[(j + it2.first) % m], one[j] + it2.second); } } one = tmp; } vector<vector<ll>> graph(m, vector<ll>(m, MAX)); for(int i = 0; i < m; i++) { for(int j = 0; j < m; j++) { graph[i][(i + j) % m] = one[j]; } } vector<ll> dist(m, MAX); vector<bool> visited(m, false); dist[0] = 0; for(int c = 0; c < m; c++) { int idx = -1; for(int i = 0; i < m; i++) { if(!visited[i]) { if(idx == -1) idx = i; else if(dist[i] < dist[idx]) idx = i; } } visited[idx] = true; for(int i = 0; i < m; i++) { if(!visited[i]) dist[i] = min(dist[i], dist[idx] + graph[idx][i]); } } for(int i = 0; i < m; i++) { if(dist[i] == MAX) cout << "-1\n"; else cout << dist[i] << '\n'; } } |