Pagini recente » Cod sursa (job #1266371) | Cod sursa (job #3037431) | Cod sursa (job #292139) | Cod sursa (job #2388329) | Cod sursa (job #3336542)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define pii pair<int, int>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int NMAX = 5e4 + 5, inf = 1e9 + 5;
const char nl = '\n';
vector<pii> g[NMAX];
int visitat[NMAX], parinte[NMAX], dist[NMAX];
int ford (int source, int size) {
for (int i = 1; i <= size;i++) {
dist[i] = inf;
visitat[i] = 0;
}
dist[source] = 0;
queue<int> q;
parinte[source] = -1;
q.push(source);
while (!q.empty()) {
int nod = q.front();
q.pop();
visitat[nod]++;
if (visitat[nod] == size) {
fout << "Ciclu negativ!" << nl;
// fout << nod << " ";
// int ciclu_nod = parinte[nod];
// while (ciclu_nod != nod) {
// fout << ciclu_nod << " ";
// ciclu_nod = parinte[ciclu_nod];
// }
return 0;
}
for (auto neigh: g[nod]) {
if (neigh.second + dist[nod] < dist[neigh.first]) {
dist[neigh.first] = dist[nod] + neigh.second;
q.push(neigh.first);
parinte[neigh.first] = nod;
}
}
}
return 1;
}
int main () {
int n, m, x, y, z;
fin >> n >> m;
for (int i = 0; i < m; i++) {
fin >> x >> y >> z;
g[x].push_back({y, z});
}
if (ford(1, n)) {
for (int i = 2; i <= n; i++) {
fout << dist[i] << " ";
}
}
else {
}
}