Pagini recente » Cod sursa (job #1377179) | Cod sursa (job #1378375) | Profil Bodirlau_Alexandra_Maria_322CA | Cod sursa (job #2467914) | Cod sursa (job #1366880)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define inf 1<<30
#define nmax 50005
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
int cost[nmax], used[nmax];
bool ok = true;
vector < pair <int, int> > G[nmax];
queue < pair<int, int> > q;
void bellmanFord(int nod) {
cost[nod] = 0;
q.push(make_pair(nod, cost[nod]));
for (; q.size();) {
int nodCurent = q.front().first;
int costCurent = q.front().second;
q.pop();
for (int i = 0; i < G[nodCurent].size(); i++) {
int vecinCurent = G[nodCurent][i].first;
int costVecin = G[nodCurent][i].second;
if (cost[vecinCurent] > costCurent + costVecin) {
cost[vecinCurent] = costCurent + costVecin;
used[vecinCurent]++;
q.push(make_pair(vecinCurent, cost[vecinCurent]));
}
if (used[vecinCurent] > n) {
ok = false;
fout << "Ciclu negativ!\n";
return;
}
}
}
}
int main() {
fin >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y, z;
fin >> x >> y >> z;
G[x].push_back(make_pair(y, z));
}
for (int i = 1; i <= n; i++)
cost[i] = inf;
bellmanFord(1);
if (ok)
for (int i = 2; i <= n; i++)
cost[i] == inf ? fout << 0 << " " : fout << cost[i] << " ";
fin.close();
fout.close();
return 0;
}