Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <vector>
- using namespace std;
- const int oo = 100000000;
- struct Muchie
- {
- int x, cost;
- };
- vector<Muchie> L[102];
- bool viz[102];
- int sursa, n;
- int d[102]; /* d[i] = infinit, daca nu exista lant de la sursa la i;
- * = j, unde j este distanta
- */
- void Citire()
- {
- ifstream fin ("dijkstra.in");
- fin >> n >> sursa;
- int x, y, c;
- while(fin >> x >> y >> c)
- {
- Muchie w;
- w.x = y;
- w.cost = c;
- L[x].push_back(w);
- }
- }
- void Dijkstra()
- {
- // Initializare d[i];
- for(int i = 1; i <= n; ++i)
- d[i] = oo;
- d[sursa] = 0; // Distanta de la sursa la sursa e 0;
- // Dijkstra are maxim (n - 1) pasi;
- for(int pas = 1; pas < n; ++pas)
- {
- int minim = oo;
- int p = 0;
- for(int i = 1; i <= n; ++i)
- if (minim > d[i] && !viz[i])
- {
- minim = d[i];
- p = i;
- }
- // Daca minimul a ramas tot infinit, atunci se termina functia;
- if (p == 0) return ;
- // Actualizarea datelor
- viz[p] = 1;
- for(unsigned int i = 0; i < L[p].size(); ++i)
- {
- int j = L[p][i].x;
- int cost = L[p][i].cost;
- if (d[j] > d[p] + cost)
- d[j] = d[p] + cost;
- }
- }
- }
- void Afisare()
- {
- ofstream fout ("dijkstra.out");
- for(int i = 1; i <= n; ++i)
- {
- if (d[i] == oo) fout << "-1 ";
- else fout << d[i] << " ";
- }
- }
- int main()
- {
- Citire();
- Dijkstra();
- Afisare();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement