Pagini recente » Cod sursa (job #1427668) | Cod sursa (job #1054343) | Cod sursa (job #1960866) | Cod sursa (job #2393826) | Cod sursa (job #1314600)
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
#define nmax 50001
#define weight first
#define node second
#define inf (1<<30)
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout ("bellmanford.out");
vector< pair<int, int> > v[nmax];
queue <int> q;
void bellman_ford(int n, int best[nmax], int cycle[nmax], bool cycle_inf){
for(int i=2; i<=n; i++) best[i]= inf;
q.push(1);
while(!q.empty()){
int current = q.front();
for(int i=0; i<v[current].size(); i++)
if(best[v[current][i].node] > best[current] + v[current][i].weight){
best[v[current][i].node]= best[current] + v[current][i].weight;
q.push(v[current][i].node);
cycle[v[current][i].node]++;
if(cycle[v[current][i].node]>n){
cycle_inf=true;
break;
}
}
if(cycle_inf) break;
q.pop();
}
if(cycle_inf) fout << "Ciclu negativ!\n";
else for(int i=2; i<=n; i++) fout << best[i] << " ";
}
int main(){
int x, y, w, i, n, m;
int best[nmax], cycle[nmax];
bool cycle_inf = false;
fin >> n >> m;
for(i=1; i<=m; i++){
fin >> x >> y >> w;
v[x].push_back(make_pair(w, y));
}
bellman_ford(n, best, cycle, cycle_inf);
return 0;
}