Pagini recente » Cod sursa (job #2125185) | Cod sursa (job #717122) | Cod sursa (job #1036496) | Cod sursa (job #1507443) | Cod sursa (job #2433140)
#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&v)const{
return cost>v.cost;
}
edge(int d=0, int c=0)
{
this->dest=d; this->cost=c;
}
}aux;
int f[NMAX];
vector<edge>g[NMAX];
priority_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.top().dest,cost=pq.top().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;
}