Pagini recente » Cod sursa (job #2227734) | Cod sursa (job #2190887) | Cod sursa (job #819535) | Cod sursa (job #2461480) | Cod sursa (job #3130272)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const long long N = 5e4 , INF = 1e9;
int n , m , dist[N + 1];
vector<pair<int , int> > v[N + 1];
queue<int> q;
bool bellman(int x){
int starting_point = x , n_added_to_q[N + 1];
dist[x] = 0;
q.push(x);
n_added_to_q[x]++;
while(!q.empty()){
int j = q.front();
q.pop();
for(int y = 0 ; y < v[j].size() ; ++y){
int neigh = v[j][y].first , dist_to_neigh = v[j][y].second;
if(dist[j] + dist_to_neigh < dist[neigh]){
n_added_to_q[neigh]++;
dist[neigh] = dist[j] + dist_to_neigh;
if(n_added_to_q[neigh] == n){
return false;
}
if(neigh != starting_point){
q.push(neigh);
}
}
}
}
return true;
}
void afis(){
for(int i = 2 ; i <= n ; i++){
out << dist[i] << ' ';
}
}
int main(){
in >> n >> m;
for(int i = 1 ; i <= m ; ++i){
int x , y , w;
in >> x >> y >> w;
v[x].push_back({y , w});
}
for(int i = 1 ; i <= n ; ++i){
dist[i] = INF;
}
if(!bellman(1)){
out << "Ciclu negativ!";
}
else{
afis();
}
}