Pagini recente » Cod sursa (job #1804520) | Cod sursa (job #1221073) | Cod sursa (job #2000587) | Cod sursa (job #2432748)
#include <bits/stdc++.h>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
#define NMAX 50001
#define inf 1e9
struct edge{
int dest,cost;
bool operator<(const edge&aux)const{
return cost>aux.cost;
}
}aux;
int f[NMAX];
vector<edge>g[NMAX];
queue<edge>pq;
int dist[NMAX];
bool bellmanford(int n){
aux.cost=0;
aux.dest=1;
pq.push(aux);
while(!pq.empty()){
int node=pq.front().dest,cost=pq.front().cost;
dist[node]=min(cost,dist[node]);
f[node]++;
pq.pop();
if(f[node]<n){
for(auto y:g[node]){
if(dist[node]+y.cost<=dist[y.dest]){
aux.dest=y.dest;
aux.cost=y.cost+dist[node];
pq.push(aux);
}
}
}
else{
out<<"Ciclu negativ!";
return 0;
}
}
return 1;
}
int main()
{
int n,m;
in>>n>>m;
int x,y,cost;
for(int i=1;i<=n;i++)
dist[i]=inf;
for(int i=1;i<=m;i++){
in>>x>>y>>cost;
aux.cost=cost;
aux.dest=y;
g[x].push_back(aux);
}
if(bellmanford(n)){
for(int i=2;i<=n;i++)
out<<dist[i]<<" ";
}
return 0;
}