Pagini recente » Cod sursa (job #2913104) | Cod sursa (job #1269358) | Cod sursa (job #1241598) | Cod sursa (job #2352038) | Cod sursa (job #2182051)
#include <fstream>
#include <vector>
#include <set>
#include <algorithm>
#define N 50005
#define M 250005
#define Inf 1<<30
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
long n, m, last;
long d[N], Pos[N];
bool ok[N];
struct muchie{
long a, b, c;
} e[M];
vector<long>A[N];
vector<pair<long,long>>Heap;
void BellmanFord()
{
pair<long,long>per;
long long nod, poz, pas=0;
while(Heap.size() && pas<=1LL*n*m)
{
pas++;
pop_heap(Heap.begin(),Heap.end());
per=Heap.back();
Heap.pop_back();
nod=per.second;
ok[nod]=0;
for(auto it:A[nod])
{
poz=it;
if(d[e[poz].a] + e[poz].c < d[e[poz].b])
{
d[e[poz].b] = d[e[poz].a] + e[poz].c;
if(!ok[e[poz].b])
{
ok[e[poz].b]=1;
Heap.push_back({-d[e[poz].b], e[poz].b});
push_heap(Heap.begin(),Heap.end());
}
}
}
}
}
int main()
{
long a,b,c;
fin>>n>>m;
for(long i=1; i<=m; i++)
{
fin>>e[i].a>>e[i].b>>e[i].c;
A[e[i].a].push_back(i);
}
for(long i=2; i<=n; i++)
d[i]=Inf;
Heap.push_back({0,1});
make_heap(Heap.begin(),Heap.end());
BellmanFord();
for(int i=1; i<=m; i++)
{
if(d[e[i].a] + e[i].c < d[e[i].b])
{
fout<<"Ciclu negativ!\n";
return 0;
}
}
for(int i=2; i<=n; i++)
fout<<d[i]<<' ';
return 0;
}