Pagini recente » Statistici Stanica Florin (florinstanica24) | Cod sursa (job #886774) | Cod sursa (job #1764488) | Cod sursa (job #652285) | Cod sursa (job #2433170)
#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;
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;
int node=pq.front().dest,cost=pq.front().cost;
//cout<<"nod:"<<node<<" "<<cost<<endl;
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];
//dist[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=1;i<=n;i++)
cout<<f[i]<<" ";
cout<<endl;*/
for(int i=2;i<=n;i++)
cout<<dist[i]<<" ";
}
return 0;
}