Pagini recente » Cod sursa (job #1635623) | Cod sursa (job #2662160) | Cod sursa (job #2132320) | Cod sursa (job #1868109) | Cod sursa (job #2479091)
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define Nmax 50001
#define INF 0x3f3f3f3f
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
struct NodCost{
int nod,cost;
bool operator <(const NodCost &var)const{
return cost>var.cost;
}
};
vector <NodCost> G[Nmax];
priority_queue <NodCost> q;
int dist[Nmax],n,m,ap[Nmax];
int BellmanFord()
{
memset(dist,INF,sizeof dist);
dist[1]=0;
ap[1]=1;
q.push({1,0});
while (!q.empty())
{
int x=q.top().nod;
int y=q.top().cost;
q.pop();
for (auto i:G[x])
{
if (dist[i.nod]>y+i.cost)
{
ap[i.nod]++;
if (ap[i.nod]==n)
return 0;
else
{
dist[i.nod]=y+i.cost;
q.push({i.nod,dist[i.nod]});
}
}
}
}
return 1;
}
int main()
{
int i,a,b,c;
fin>>n>>m;
for (i=1;i<=m;i++)
{
fin>>a>>b>>c;
G[a].push_back({b,c});
}
int x=BellmanFord();
if (x==1)
{
for (i=2;i<=n;i++)
fout<<dist[i]<<" ";
}
else
fout<<"Ciclu negativ!";
return 0;
}