Advertisement
radmickey

Untitled

Mar 28th, 2023
706
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <limits>
  5.  
  6. using namespace std;
  7.  
  8. struct Edge {
  9.     int from;
  10.     int to;
  11.     int weight;
  12. };
  13.  
  14. int main() {
  15.     int N, M, S, T;
  16.     cin >> N >> M >> S >> T;
  17.  
  18.     vector<vector<Edge>> graph(N + 1);
  19.  
  20.     for (int i = 0; i < M; i++) {
  21.         int a, b, w;
  22.         cin >> a >> b >> w;
  23.         graph[a].push_back({a, b, w});
  24.     }
  25.  
  26.     vector<int> dist(N + 1, numeric_limits<int>::max());
  27.     dist[S] = 0;
  28.  
  29.     priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
  30.     pq.push({0, S});
  31.  
  32.     while (!pq.empty()) {
  33.         int current_dist = pq.top().first;
  34.         int current_vertex = pq.top().second;
  35.         pq.pop();
  36.  
  37.         if (current_dist > dist[current_vertex]) continue;
  38.  
  39.         for (const Edge& edge: graph[current_vertex]) {
  40.             int new_dist = current_dist + edge.weight;
  41.             if (new_dist < dist[edge.to]) {
  42.                 dist[edge.to] = new_dist;
  43.                 pq.push({new_dist, edge.to});
  44.             }
  45.         }
  46.     }
  47.  
  48.     if (dist[T] == numeric_limits<int>::max()) {
  49.         cout << -1 << endl;
  50.     } else {
  51.         cout << dist[T] << endl;
  52.     }
  53.  
  54.     return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement