Pagini recente » Cod sursa (job #2135896) | Cod sursa (job #418023) | Cod sursa (job #1238694) | Cod sursa (job #1729725) | Cod sursa (job #3032525)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");
struct elem{
int nod,cost;
bool operator < (const elem &aux)
const{
return aux.cost<cost;
}
};
int dist[50001],fr[50001];
priority_queue < elem>q;
vector<pair<int,int>>adiacenta[50001];
int n,m;
void bell()
{
for(int i = 1;i<=n;i++)
dist[i]=(1<<30)-1;
dist[1] = 0;
q.push({1,0});
while(!q.empty())
{
int curent = q.top().nod;
int cost_curent = q.top().cost;
q.pop();
fr[curent]++;
if(fr[curent]>n)
{
g << "Ciclu negativ!";
exit();
}
for(auto x:adiacenta[curent])
{
int nod_nou = x.first;
int cost_nou = x.second;
if(dist[nod_nou]>cost_curent+cost_nou)
{
dist[nod_nou]= cost_curent+cost_nou;
q.push({nod_nou,dist[nod_nou]});
}
}
}
}
int main()
{
f >> n >> m;
for(int i=1;i<=n;i++)
{
int x,y,c;
f >> x >> y >> c;
adiacenta[x].push_back({y,c});
}
bell();
for(int i = 2;i<=n;i++)
g << dist[i]<< " ";
}