Pagini recente » Cod sursa (job #2328458) | Cod sursa (job #2811401) | Cod sursa (job #675642) | Cod sursa (job #2739767) | Cod sursa (job #2574922)
#include <bits/stdc++.h>
#define NMAX 50005
#define inf INT_MAX
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
vector< pair<int, int> > G[NMAX];
int n,m;
vector< int > cost(NMAX, inf);
bitset<NMAX> inq;
vector< int > times(NMAX);
void dijkstra(){
queue<int> PQ;
cost[1]=0;
PQ.push(1);
while(!PQ.empty()){
int nd = PQ.front();
inq[nd]=false;
PQ.pop();
for(auto it: G[nd]){
if(cost[it.first]> cost[nd]+it.second){
cost[it.first]=cost[nd] + it.second;
if(!inq[it.first]){
if(times[it.first]>n){
g<<"Ciclu negativ!";
return;
}
PQ.push(it.first);
times[it.first]++;
inq[it.first]=true;
}
}
}
}
}
int main()
{
f>>n>>m;
for(int i=1,x,y,c;i<=m;i++){
f>>x>>y>>c;
G[x].push_back(make_pair(y,c));
}
dijkstra();
for(int i=2;i<=n;i++)
g<<cost[i]<<' ';
return 0;
}