irapilguy

Untitled

Nov 28th, 2017
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. using namespace std;
  2. #define N 101
  3. #define INF 1000000
  4. vector <int> graph[N];
  5. int way[N] = {-1};
  6. int lenght[N];
  7. int used[N];
  8. int n;
  9. void bfs(int start) {
  10.     queue<int>q;
  11.     q.push(start);
  12.     used[start] = 1;
  13.     while (q.size() != 0) {
  14.         start = q.front();
  15.         q.pop();
  16.         for (int i = 0; i < n; i++) {
  17.             if ( used[i] == 0 && graph[start][i] != -1) {
  18.                 q.push(i);
  19.                 way[i ] = i;
  20.                 used[i] = 1;
  21.                
  22.             }
  23.             int per = graph[start][i] + lenght[start];
  24.             if (lenght[i] != 0 && graph[start][i] != -1 && lenght[i] > per) {
  25.                 lenght[i] = per;
  26.                 q.push(i);
  27.                 way[i] = i;
  28.             }
  29.         }
  30.     }
  31. }
  32. int main() {
  33.     int start, finish;
  34.     cin >> n >> start >> finish;
  35.     for (int j = 0; j < n; j++) {
  36.         for (int i = 0; i < n; i++) {
  37.             int x;
  38.             cin >> x;
  39.             graph[i].push_back(x);
  40.         }
  41.     }
  42.     for (int i = 0; i < n; i++) lenght[i] = INF;
  43.     lenght[start - 1] = 0;
  44.     bfs(start - 1);
  45.     cout << "lenght " << lenght[finish - 1] << "\n";
  46.     cout << start << "  ";
  47.     int i = 0;
  48.     while (way[i] != -1) {
  49.         cout << way[i] + 1 << " ";
  50.         i++;
  51.     }
  52.     return 0;
  53. }
Add Comment
Please, Sign In to add comment