Mai intai trebuie sa te autentifici.
Cod sursa(job #1706656)
Utilizator | Data | 22 mai 2016 22:27:15 | |
---|---|---|---|
Problema | Algoritmul lui Dijkstra | Scor | 30 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 1.11 kb |
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
const int inf = 1001;
const int NMAX = 51000;
int n,m;
int d[NMAX];
vector <int> graph[NMAX], cost[NMAX];
void Bellman_Ford(int vertex)
{ queue <int> q;
int c, x, y, length;
for (int i=1;i<=n;i++)
d[i]=inf;
d[vertex]=0;
q.push(vertex);
while(!q.empty())
{ x=q.front();
q.pop();
length=graph[x].size();
for (int i = 0; i < length; i++)
{ y=graph[x][i];
c=cost[x][i];
if (d[y]>d[x]+c)
{ d[y]=d[x]+c;
q.push(y);
}
}
}
}
void afisare()
{ for (int i = 1; i <= n; i++)
{ if (i == 1) continue;
if (d[i] == inf) d[i] = 0;
g<<d[i]<<' ';
}
g << '\n';
}
int main()
{ int x,y,z;
f>>n>>m;
for (int i = 1; i <= m; i++)
{ f>>x>>y>>z;
graph[x].push_back(y);
cost[x].push_back(z);
}
Bellman_Ford(1);
afisare();
return 0;
}