Pagini recente » Cod sursa (job #2217130) | Cod sursa (job #520447) | Cod sursa (job #898216) | Cod sursa (job #2189074) | Cod sursa (job #2999374)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
///#include <tryhardmode>
///#include <GODMODE::ON>
///PRACTICE
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
const int NMAX=5e5+5;
const int INF=1e9;
struct elem{
int cost;
int node;
bool operator<(const elem &other) const
{
return cost>other.cost;
}
};
priority_queue<elem>q;
vector<pair<int,int>>v[NMAX];
bool flag;
int dist[NMAX];
int viz[NMAX];
int n;
void bellman(int p)
{
dist[p]=0;
q.push({0,1});
while(!q.empty())
{
elem p=q.top();
q.pop();
for(auto i:v[p.node])
{
if(dist[i.first]>dist[p.node]+i.second)
{
dist[i.first]=dist[p.node]+i.second;
elem aux;
aux.node=i.first;
aux.cost=dist[i.first];
q.push(aux);
viz[i.first]++;
if(viz[i.first]==n)
{
flag=true;
return ;
}
}
}
}
}
int main()
{
int m,i,j;
fin>>n>>m;
for(i=1;i<=m;i++)
{
int x,y,c;
fin>>x>>y>>c;
v[x].push_back(make_pair(y,c));
}
for(i=1;i<=n;i++)
dist[i]=INF;
bellman(1);
if(flag)
fout<<"Ciclu negativ!\n";
else
{
for(i=2;i<=n;i++)
fout<<dist[i]<<" ";
}
return 0;
}