Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<pair<int, int>> graph[2001];
  5. int distances[2001];
  6.  
  7. int main() {
  8.     ios_base::sync_with_stdio(false);
  9.     cin.tie(NULL);
  10.     freopen("pathmgep.in", "r", stdin);
  11.     freopen("pathmgep.out", "w", stdout);
  12.     int n, start, finish;
  13.     cin >> n >> start >> finish;
  14.     start--;
  15.     finish--;
  16.     for (int i = 0; i < n; ++i) {
  17.         for (int j = 0; j < n; ++j) {
  18.             int weight;
  19.             cin >> weight;
  20.             if (weight != 0 && weight != -1) {
  21.                 graph[i].push_back({j, weight});
  22.             }
  23.         }
  24.     }
  25.  
  26.     for (int i = 0; i < n; i++) {
  27.         distances[i] = 1e9 + 1;
  28.     }
  29.  
  30.     distances[start] = 0;
  31.  
  32.     priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
  33.  
  34.     q.push({start, 0});
  35.  
  36.     while (!q.empty()) {
  37.         pair<int, int> top = q.top();
  38.         q.pop();
  39.  
  40.         int v = top.first, dst = top.second;
  41.  
  42.         if (distances[v] < dst) {
  43.             continue;
  44.         }
  45.  
  46.         for (pair<int, int> e: graph[v]) {
  47.             int u = e.first, len_vtou = e.second;
  48.  
  49.             int new_dst = dst + len_vtou;
  50.             if (new_dst < distances[u]) {
  51.                 distances[u] = new_dst;
  52.                 q.push({u, new_dst});
  53.             }
  54.         }
  55.     }
  56.     if (distances[finish] != 1e9 + 1) {
  57.         cout << distances[finish] << endl;
  58.     } else cout << -1 << endl;
  59.     return 0;
  60. }
  61.  
  62. /*
  63.   3 1 2
  64.   0 -1 2
  65.   3 0 -1
  66.   -1 4 0
  67.  
  68.  3 1 2
  69.  0 -1 2
  70.  3 0 -1
  71.  -1 -1 0
  72.  
  73.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement