Pagini recente » Cod sursa (job #2618699) | Cod sursa (job #420772) | Cod sursa (job #1826723) | Cod sursa (job #1766756) | Cod sursa (job #2432248)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int MAXN = 5 * 1e4 + 5;
struct EDGE{
int dest, cost;
};
vector <EDGE> g[MAXN];
queue <int> q;
int dist[MAXN], viz[MAXN];
bool ok = true;
void ALG(int n){
q.push(1);
while(q.size()){
int node = q.front();
q.pop();
for(auto y : g[node]){
if(dist[y.dest] > dist[node] + y.cost){
q.push(y.dest);
dist[y.dest] = dist[node] + y.cost;
viz[y.dest]++;
if(viz[y.dest] == n) {
ok = false;
break;
}
}
}
}
}
int main()
{
int n, m, s;
fin >> n >> m;
for(int i = 1; i <= m; ++i){
int x, y, c;
fin >> x >> y >> c;
g[x].push_back({y, c});
}
for(int i = 2; i <= n; ++i) dist[i] = MAXN;
ALG(n);
if(!ok) {
fout << "Ciclu negativ!";
return 0;
}
for(int i = 2; i <= n; ++i) fout << dist[i] << " " ;
return 0;
}