Pagini recente » Cod sursa (job #2313198) | Cod sursa (job #2395314) | Cod sursa (job #257715) | Cod sursa (job #68820) | Cod sursa (job #3182925)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
struct edge{
int u,v,c;
edge(int _u, int _v, int _c){
u = _u;
v = _v;
c = _c;
}
};
int d[50005];
int cnt[50005];
int n;
bool cn;
vector < pair <int, int> > G[50005];
queue <int> q;
bool inqueue[50005];
bool bellman_ford(){
d[1] = 0;
q.push(1);
inqueue[1] = 1;
while(!q.empty()){
for(auto x : G[q.front()]){
if(d[q.front()] + x.second < d[x.first]){
d[x.first] = d[q.front()] + x.second;
if(!inqueue[x.first]){
q.push(x.first);
inqueue[x.first] = 1;
cnt[x.first]++;
if(cnt[x.first] > n) return 0;
}
}
}
q.pop();
}
return 1;
}
int main()
{
int m,i,u,v,c;
fin >> n >> m;
memset(d,0x3f,sizeof d);
for(i = 1; i <= m; i++){
fin >> u >> v >> c;
G[u].push_back({v,c});
}
if(!bellman_ford()){
fout << "Ciclu negativ!";
return 0;
}
for(i = 2; i <= n; i++) fout << d[i] << " ";
return 0;
}