Pagini recente » Cod sursa (job #227107) | Cod sursa (job #10077) | Cod sursa (job #2264008) | Cod sursa (job #1591224) | Cod sursa (job #2839323)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
const int N=25e2+5;
const int INF=2e9;
const int START=1;
int n,m;
int cont[N+5];
vector <int> d(N+5,INF);
vector <pair <int,int>> adj[N];
bool inQueue[N+5];
bool bellmanFord(){
queue <int> q;
q.push(START);
d[START]=0;
cont[START]=inQueue[START]=1;
while(!q.empty()){
int node=q.front();
q.pop();
inQueue[node]=0;
for(auto it:adj[node]){
if(d[node]+it.second<d[it.first]){
d[it.first]=d[node]+it.second;
if(!inQueue[it.first]){
q.push(it.first);
inQueue[it.first]=1;
cont[it.first]++;
if(cont[it.first]==n)
return 0;
}
}
}
}
return 1;
}
int main()
{
cin>>n>>m;
for(int i=1; i<=m; i++){
int x,y,c;
cin>>x>>y>>c;
adj[x].push_back({y,c});
}
if(!bellmanFord())
cout<<"Ciclu negativ!\n";
else{
for(int i=2; i<=n; i++)
cout<<d[i]<<" ";
cout<<'\n';
}
return 0;
}