Loading...
Submission
Id When Author Problem Language CPU Memory Verdict
50353 2026-03-13 21:54:28 cyblox บินประหยัด จำกัดเที่ยว (K-Stops Flights) C++ 17 7 ms 3492 kb Accepted
Test Cases
CPU Memory Verdict
1 6 ms 3332 kb Accepted
2 7 ms 3436 kb Accepted
3 6 ms 3372 kb Accepted
4 7 ms 3488 kb Accepted
5 6 ms 3492 kb Accepted
Source Code
program.cpp
Download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Edge
  5. {
  6. int v, w;
  7. };
  8.  
  9. typedef map<int, vector<Edge>> AdjList;
  10.  
  11. struct State
  12. {
  13. int cost, u, stops;
  14.  
  15. bool operator>(const State &other) const
  16. {
  17. return cost > other.cost;
  18. }
  19. };
  20.  
  21. int dijkstra(AdjList &adj, int s, int e, int k)
  22. {
  23. priority_queue<State, vector<State>, greater<State>> pq;
  24. map<int, vector<int>> dist;
  25.  
  26. for (const auto &p : adj)
  27. {
  28. dist[p.first] = vector<int>(k + 2, INT_MAX);
  29. }
  30.  
  31. dist[s][0] = 0;
  32.  
  33. pq.push({0, s, 0});
  34.  
  35. while (!pq.empty())
  36. {
  37. auto [cost, u, stops] = pq.top();
  38.  
  39. pq.pop();
  40.  
  41. if (u == e)
  42. {
  43. return cost;
  44. }
  45.  
  46. if (stops > k)
  47. {
  48. continue;
  49. }
  50.  
  51. for (const auto &edge : adj[u])
  52. {
  53. int newCost = cost + edge.w;
  54.  
  55. if (newCost < dist[edge.v][stops + 1])
  56. {
  57. dist[edge.v][stops + 1] = newCost;
  58.  
  59. pq.push({newCost, edge.v, stops + 1});
  60. }
  61. }
  62. }
  63.  
  64. return -1;
  65. }
  66.  
  67. int main()
  68. {
  69. ios::sync_with_stdio(false);
  70. cin.tie(nullptr);
  71.  
  72. int n, m, k;
  73. cin >> n >> m >> k;
  74.  
  75. int s, e;
  76. cin >> s >> e;
  77.  
  78. AdjList adj;
  79.  
  80. for (int i = 1; i <= n; i++)
  81. {
  82. adj[i] = {};
  83. }
  84.  
  85. for (int i = 0; i < m; i++)
  86. {
  87. int u, v, w;
  88. cin >> u >> v >> w;
  89.  
  90. adj[u].push_back({v, w});
  91. }
  92.  
  93. cout << dijkstra(adj, s, e, k) << '\n';
  94.  
  95. return 0;
  96. }
  97.