Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. const int oo = 100000000;
  7.  
  8. struct Muchie
  9. {
  10. int x, cost;
  11. };
  12.  
  13. vector<Muchie> L[102];
  14. bool viz[102];
  15.  
  16. int sursa, n;
  17. int d[102]; /* d[i] = infinit, daca nu exista lant de la sursa la i;
  18. * = j, unde j este distanta
  19. */
  20.  
  21. void Citire()
  22. {
  23. ifstream fin ("dijkstra.in");
  24. fin >> n >> sursa;
  25.  
  26. int x, y, c;
  27. while(fin >> x >> y >> c)
  28. {
  29. Muchie w;
  30. w.x = y;
  31. w.cost = c;
  32. L[x].push_back(w);
  33. }
  34. }
  35.  
  36. void Dijkstra()
  37. {
  38. // Initializare d[i];
  39. for(int i = 1; i <= n; ++i)
  40. d[i] = oo;
  41. d[sursa] = 0; // Distanta de la sursa la sursa e 0;
  42.  
  43. // Dijkstra are maxim (n - 1) pasi;
  44. for(int pas = 1; pas < n; ++pas)
  45. {
  46. int minim = oo;
  47. int p = 0;
  48. for(int i = 1; i <= n; ++i)
  49. if (minim > d[i] && !viz[i])
  50. {
  51. minim = d[i];
  52. p = i;
  53. }
  54. // Daca minimul a ramas tot infinit, atunci se termina functia;
  55. if (p == 0) return ;
  56.  
  57. // Actualizarea datelor
  58. viz[p] = 1;
  59. for(unsigned int i = 0; i < L[p].size(); ++i)
  60. {
  61. int j = L[p][i].x;
  62. int cost = L[p][i].cost;
  63. if (d[j] > d[p] + cost)
  64. d[j] = d[p] + cost;
  65. }
  66. }
  67. }
  68.  
  69. void Afisare()
  70. {
  71. ofstream fout ("dijkstra.out");
  72. for(int i = 1; i <= n; ++i)
  73. {
  74. if (d[i] == oo) fout << "-1 ";
  75. else fout << d[i] << " ";
  76. }
  77. }
  78.  
  79. int main()
  80. {
  81. Citire();
  82. Dijkstra();
  83. Afisare();
  84. return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement