Pagini recente » Cod sursa (job #2041799) | Cod sursa (job #2193635) | Cod sursa (job #2161382) | Cod sursa (job #1405014) | Cod sursa (job #1370847)
#include <iostream>
#include <queue>
#include <fstream>
#define nmax 50005
#define inf (1<<30)
#define value first
#define node second
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
vector< pair<int, int> > v[nmax];
queue <int> q;
int number_of_nodes, number_of_edges;
int previous[nmax], cycle[nmax], best[nmax];
void bellman(){
for(int i=2; i<=number_of_nodes; i++) best[i]= inf;
q.push(1);
while(!q.empty()){
int current= q.front();
q.pop();
for(int i=0; i<v[current].size(); i++){
int neigh= v[current][i].node;
int neigh_value= v[current][i].value;
if(best[neigh] > best[current]+ neigh_value){
best[neigh]= best[current]+ neigh_value;
cycle[neigh]++;
previous[neigh]= current;
q.push(neigh);
if(cycle[neigh] > number_of_nodes){
fout << "Ciclu negativ!\n";
return;
}
}
}
}
for(int i=2; i<=number_of_nodes; i++)
if(best[i]==inf) fout << 0 << " ";
else fout << best[i] << " ";
}
int main(){
int x, y, w;
fin >> number_of_nodes >> number_of_edges;
for(int i=1; i<=number_of_edges; i++){
fin >> x >> y >> w;
v[x].push_back(make_pair(w, y));
}
bellman();
return 0;
}