danielvitor23

L - Walking to School

Jul 13th, 2023
1,231
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 1 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using ii = pair<int, int>;
  5. using i64 = long long;
  6.  
  7. const int INF = 0x3f3f3f3f;
  8.  
  9. int n, m, T;
  10. vector<vector<ii>> gr;
  11.  
  12. i64 dijkstra(int source) {
  13.   vector<i64> dist(n+1, INF);
  14.  
  15.   dist[source] = 0;
  16.  
  17.   priority_queue<tuple<i64, i64, int>> pq;
  18.   pq.push({ 0, 0, source });
  19.  
  20.   while (!pq.empty()) {
  21.     auto [d, r, u] = pq.top(); pq.pop();
  22.  
  23.     if (d > dist[u]) continue;
  24.  
  25.     for (auto [w, to] : gr[u]) {
  26.       if (dist[u] + r * w < dist[to]) {
  27.         dist[to] = dist[u] + r * w;
  28.  
  29.         pq.push({ dist[to], r + (w == 0 ? 0 : 1), to });
  30.       }
  31.     }
  32.   }
  33.  
  34.   return dist[T] == INF ? -1 : dist[T];
  35. }
  36.  
  37. int main() {
  38.   cin.tie(0)->sync_with_stdio(0);
  39.  
  40.   cin >> n >> m >> T, --T;
  41.  
  42.   gr.assign(n, vector<ii>());
  43.  
  44.   for (int i = 0; i < m; ++i) {
  45.     int a, b, c; cin >> a >> b >> c, --a, --b;
  46.  
  47.     gr[a].push_back({ c, b });
  48.     gr[b].push_back({ c, a });
  49.   }
  50.  
  51.   cout << dijkstra(0) << '\n';
  52. }
Advertisement
Add Comment
Please, Sign In to add comment