Mattia-Iojica

Dijkstra

Sep 22nd, 2019
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.27 KB | None | 0 0
  1. #include    <iostream>
  2. #include    <fstream>
  3. #include    <queue>
  4. #include    <vector>
  5.  
  6. using namespace std;
  7.  
  8. ifstream fin("dijkstra.in");
  9. ofstream fout("dijkstra.out");
  10.  
  11. const int NMax = 50005;
  12. const int oo = (1 << 30); // constanta infinit
  13. int N, M;
  14. int D[NMax]; // vector de distanta
  15. bool InCoada[NMax]; //stocheaza cand un nod intra in coada
  16.  
  17. vector < pair < int, int > > G[NMax]; //vector de perechi
  18.  
  19. struct ComparaDistante // functie care ordoneaza min si max
  20. {
  21.     bool operator()(int x,int y) // x si y -nodurile pe care coada le compara
  22.     {
  23.         return D[x] > D[y];
  24.     }
  25. };
  26.  
  27. priority_queue < int, vector < int >,ComparaDistante > Coada;
  28.  
  29. void Citire()
  30. {
  31.     fin >> N >> M;
  32.     for(int i = 1; i <= M; i++)
  33.     {
  34.         int x, y, c;
  35.         fin >> x >> y >> c;
  36.         G[x].push_back(make_pair(y, c)); // punem in G[x] toti vecinii y care au costul c
  37.     }
  38. }
  39.  
  40. void Afiseaza()
  41. {
  42.     for(int i = 2; i <= N; i++) // i = 2 pt ca nodul de start e 1 ( "Dijkstra(1)" )
  43.         if(D[i] != oo)
  44.         fout << D[i] << " ";
  45.     else
  46.         fout << "0 ";
  47. }
  48.  
  49. void Dijkstra(int nodStart)
  50. {
  51.     for(int i = 1; i <= N; i++)
  52.         D[i] = oo; // incepem cu toate distantele fiind oo
  53.  
  54.     D[nodStart]=0; // distanta la nodul de start = 0
  55.     Coada.push(nodStart); // punem nodul de start in coada
  56.     InCoada[nodStart] = true; // marcam nodul ca fiind in coada
  57.     while(!Coada.empty()) // cat timp coada nu e goala
  58.     {
  59.         int nodCurent = Coada.top(); // extragem nodul curent
  60.         Coada.pop(); // il eliminam
  61.         InCoada[nodCurent] = false; //nodul curent nu mai face parte din coada
  62.  
  63.         for(size_t i = 0; i < G[nodCurent].size(); i++)
  64.        {
  65.             int Vecin = G[nodCurent][i].first;
  66.             int Cost = G[nodCurent][i].second;
  67.             if(D[nodCurent] + Cost < D[Vecin])
  68.            {
  69.                D[Vecin] = D[nodCurent] + Cost;
  70.                if(InCoada[Vecin] == false) // daca vecinul nu se afla in coada
  71.                 {
  72.             Coada.push(Vecin); // adaugam vecinul in coada
  73.             InCoada[Vecin] = true; //marcam vecinul ca fiind in coada
  74.                 }
  75.            }
  76.         }
  77.     }
  78. }
  79.  
  80. int main()
  81. {
  82.     Citire();
  83.     Dijkstra(1);
  84.     Afiseaza();
  85.     return 0;
  86. }
Add Comment
Please, Sign In to add comment