Pagini recente » Cod sursa (job #2911424) | Cod sursa (job #1820897) | Cod sursa (job #1572815) | Cod sursa (job #1096884) | Cod sursa (job #3251606)
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int oo=2000000009;
queue < int > q;
vector < pair < int , int > > v[50005];
int dist[50005];
int n, m, x, y, c;
int ok=1;
int viz[50005];
int inqueue[50005];
int main()
{
f >> n >> m;
for (int i=1;i<=m;i++) {
f >> x >> y >> c;
v[x].push_back({y, c});
}
for (int i=1;i<=n;i++) {
dist[i] = oo;
}
dist[1] = 0;
q.push(1);
inqueue[1] = 1;
while (!q.empty() && ok == 1) {
int nod = q.front();
q.pop();
inqueue[nod] = 0;
viz[nod]++;
if (viz[nod] >= n) {
ok = 0;
break;
}
for (auto ed: v[nod]) {
if (dist[ed.first] > dist[nod] + ed.second) {
dist[ed.first] = dist[nod] + ed.second;
if (inqueue[ed.first] == 0) {
q.push(ed.first);
inqueue[ed.first] = 1;
}
}
}
}
if (ok == 1) {
for (int i=2;i<=n;i++) {
g << dist[i]<<" ";
}
}
else {
g << "Ciclu negativ!";
}
return 0;
}