Pagini recente » Cod sursa (job #2980932) | Cod sursa (job #1620247) | Cod sursa (job #1837536) | Cod sursa (job #1532767) | Cod sursa (job #2696475)
#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
int n, m, x, y, c;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
vector<vector<pii>> arches;
vector<int> nr_visits, distances;
vector<bool> visited;
queue<int> q;
bool BellmanFord(){
distances[0] = 0;
q.push(0);
nr_visits[0]++;
while(!q.empty()){
int current = q.front();
q.pop();
visited[current] = false;
for(auto itr: arches[current])
if(distances[current] + itr.second < distances[itr.first]) {
distances[itr.first] = distances[current] + itr.second;
if(!visited[itr.first]){
q.push(itr.first);
visited[itr.first] = true;
if(++nr_visits[itr.first]>n)
return false;
}
}
}
return true;
}
int main(){
f>>n>>m;
arches.resize(n+1);
nr_visits.resize(n+1, 0);
visited.resize(n+1, false);
distances.resize(n, 2e9);
for(int i=0;i<m;i++){
f>>x>>y>>c;
arches[x-1].push_back({y-1, c});
}
if(!BellmanFord()){
g<<"Ciclu negativ!";
return 0;
}
for(int i=1;i<n;++i)
g<<distances[i]<<" ";
return 0;
}