egogoboy

Дейкстра

Aug 9th, 2022
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. #include<iostream>
  2. #include<fstream>
  3. #include<vector>
  4.  
  5. using namespace std;
  6. int inf = 1000000;
  7.  
  8. int main() {
  9.  
  10.     ifstream fin("input.txt");
  11.     ofstream fout("output.txt");
  12.  
  13.     int n, st, fn;
  14.     fin >> n >> st >> fn;
  15.     --st; --fn;
  16.     vector<vector<int>> mas(n, vector<int>(n));
  17.     for (int i = 0; i < n; ++i) {
  18.         for (int j = 0; j < n; ++j) {
  19.             fin >> mas[i][j];
  20.         }
  21.     }
  22.     pair<bool, int> temp;
  23.     temp.first = false; temp.second = inf;
  24.     vector<pair<bool, int>> w(n, temp);
  25.     w[st].second = 0;
  26.     int v = st;
  27.  
  28.     for (int i = 0; i < mas.size(); ++i) {
  29.         int minimal = inf;
  30.         for (int j = 0; j < mas.size(); ++j) {
  31.             if (!w[j].first && w[j].second <= minimal) {
  32.                 minimal = w[j].second;
  33.                 v = j;
  34.             }
  35.         }
  36.         w[v].first = true;
  37.         for (int j = 0; j < mas.size(); ++j) {
  38.             if (mas[v][j] != -1)
  39.                 w[j].second = min(w[j].second, w[v].second + mas[v][j]);
  40.         }
  41.     }
  42.  
  43.     if (w[fn].second == inf) {
  44.         fout << -1 << endl;
  45.         return 0;
  46.     }
  47.  
  48.     fout << w[fn].second << endl;
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment