irapilguy

Untitled

Apr 17th, 2018
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include<queue>
  4. using namespace std;
  5. #define N 110
  6. #define INF 1000000
  7. vector <int> graph[N];
  8. int way[N];
  9. int length[N];
  10. int used[N];
  11. int n;
  12. struct El {
  13.     int ver;
  14.     int len;
  15.     El (int v, int l){
  16.         ver = v;
  17.         len = l;
  18.     }
  19. };
  20. struct compare
  21.  {
  22.    bool operator()(const El& l, const El& r)
  23.    {
  24.        return l.len > r.len;
  25.    }
  26.  };
  27. priority_queue<El, vector<El>, compare >heap;
  28. void bfs(int start) {
  29.         heap.push(El(start,0));
  30.         used[start] = 1;
  31.         while (heap.size() != 0) {
  32.                 int v = (heap.top()).ver;
  33.                 used[v] = 1;
  34.                 heap.pop();
  35.                 for (int i = 1; i <= n; i++) {
  36.                         if(graph[v][i] != -1 && used[i] == 0){
  37.                             heap.push(El(i, graph[v][i]));
  38.                         }
  39.                         int per = graph[v][i] + length[v];
  40.                         if(length[i] != 0 && graph[v][i]!= -1 && length[i] > per ){
  41.                             length[i] = per;
  42.                             way[i] = v;
  43.                             }
  44.                 }
  45.         }
  46. }
  47.  
  48. int showWay(int fin){
  49.     if (way[fin] == 0 ) return -1;
  50.     showWay(way[fin]);
  51.     cout<< way[fin] << " " ;
  52.     return 0;
  53. }
  54.  
  55. int main() {
  56.     int start, finish;
  57.     cin >> n >> start >> finish;
  58.     for (int j = 1; j <= n; j++) {
  59.                 for (int i = 1; i <= n; i++) {
  60.                         int x;
  61.                         cin >> x;
  62.                         if ( i == 1) { // из-за нумерацию с 1
  63.                             graph[j].push_back(-1);
  64.                         }
  65.                         graph[j].push_back(x);
  66.                 }
  67.         }
  68.  
  69.         for (int i = 1; i <= n; i++) length[i] = INF;
  70.         length[start] = 0;    
  71.         if ( start == finish) {
  72.             cout << start << endl;
  73.             return 0;
  74.         }
  75.         bfs(start);
  76.         if ( showWay(finish) == -1 ) {
  77.             cout << "-1";
  78.         } else {
  79.             cout << finish << endl;
  80.         }
  81.         return 0;
  82. }
Add Comment
Please, Sign In to add comment