Pagini recente » Cod sursa (job #2716429) | Cod sursa (job #2798167) | Cod sursa (job #517219) | Cod sursa (job #3120475) | Cod sursa (job #2834250)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
const int N=5e4+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];
bitset <N> inQueue;
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].emplace_back(y, c);
}
if(!bellmanFord())
cout<<"Ciclu negativ!\n";
else{
for(int i=2; i<=n; i++)
cout<<d[i]<<' ';
cout<<'\n';
}
return 0;
}