Pagini recente » Cod sursa (job #1840177) | Cod sursa (job #84392) | Cod sursa (job #1530527) | Cod sursa (job #63062) | Cod sursa (job #2542449)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int Nmax = 50000, inf = 0x3f3f3f3f;
vector <pair <int, int>> g[Nmax + 5];
queue <int> q;
int n, m, node, other, cost;
int d[Nmax + 5], nrq[Nmax + 5];
bool inq[Nmax + 5];
void Read(){
fin >> n >> m;
for (int i = 1; i <= m; i++){
int x, y, z;
fin >> x >> y >> z;
g[x].push_back({y, z});
}
}
int BellmanFord(){
memset(d, inf, sizeof d);
q.push(1);
d[1] = 0;
inq[1] = 1;
nrq[1]++;
while (!q.empty()){
node = q.front();
q.pop();
inq[node] = 0;
for (auto i : g[node]){
other = i.first;
cost = i.second;
if (d[other] > d[node] + cost){
d[other] = d[node] + cost;
if (!inq[other]){
q.push(other);
inq[other] = 1;
nrq[other]++;
if (nrq[other] > n)
return 0;
}
}
}
}
return 1;
}
void Print(){
if (!BellmanFord())
fout << "Ciclu negativ!";
else
for (int i = 2; i <= n; i++)
fout << d[i] << ' ';
fout << '\n';
}
int main(){
Read();
Print();
return 0;
}