Pagini recente » Cod sursa (job #10527) | Cod sursa (job #1236763) | Cod sursa (job #746741) | Cod sursa (job #1196524) | Cod sursa (job #1698172)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f ("dijkstra.in");
ofstream g ("dijkstra.out");
const int INF = 0x7fffffff;
const int NMAX = 50000 + 1;
int n, m;
int sol[NMAX];
vector <int> graf[NMAX], cost[NMAX];
void citeste() {
int a, b, c;
f >> n >> m;
for (int i = 1; i <= m; i++) {
f >> a >> b >> c;
graf[a].push_back(b);
cost[a].push_back(c);
}
}
void Bellman_Ford(int sursa) {
queue <int> Q;
int cost_crt, nod1, nod2, l;
for (int i = 1; i <= n; i++) sol[i] = INF;
sol[sursa] = 0;
Q.push(sursa);
while(!Q.empty()) {
nod1 = Q.front();
Q.pop();
l = graf[nod1].size();
for (int i = 0; i < l; i++) {
nod2 = graf[nod1][i];
cost_crt = cost[nod1][i];
if (sol[nod2] > sol[nod1] + cost_crt) {
sol[nod2] = sol[nod1] + cost_crt;
Q.push(nod2);
}
}
}
}
void scrie(int sursa) {
for (int i = 1; i <= n; i++) {
if (i == sursa) continue;
if (sol[i] == INF) sol[i] = 0;
g << sol[i] << ' ';
}
g << '\n';
}
int main() {
citeste();
Bellman_Ford(1);
scrie(1);
return 0;
}