Pagini recente » Cod sursa (job #2186202) | Cod sursa (job #494830) | Cod sursa (job #993054) | Cod sursa (job #3225005) | Cod sursa (job #2860792)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int NMAX = 50001;
const int inf = 1 << 30;
int N, D[NMax], vizitat[NMax], ok;
bool inCoada[NMax];
vector < pair<int, int> > G[NMax];
struct Compara
{
bool operator() (int x, int y)
{
return D[x] > D[y];
}
};
priority_queue < int, vector<int>, Compara > Coada;
void Citire()
{
int A, B, C, M;
fin >> N >> M;
for(int i=1; i<=M; ++i)
{
fin >> A >> B >> C;
G[A].push_back( make_pair(B, C) );
}
}
void BellmanFord(int nodStart)
{
for(int i=1; i<=N; ++i)
{
D[i] = inf;
vizitat[i] = 0;
}
ok = 0;
D[nodStart] = 0;
Coada.push(nodStart);
inCoada[nodStart] = true;
while( !Coada.empty() )
{
int nodCurent = Coada.top();
Coada.pop();
inCoada[nodCurent] = false;
vizitat[nodCurent] ++;
if(vizitat[nodCurent] >= N)
{
ok = 1;
break;
}
for(unsigned int i = 0; i < G[nodCurent].size(); ++i)
{
int Vecin = G[nodCurent][i].first;
int Cost = G[nodCurent][i].second;
if(D[nodCurent] + Cost < D[Vecin])
{
D[Vecin] = D[nodCurent] + Cost;
if(inCoada[Vecin] == false)
{
Coada.push(Vecin);
inCoada[Vecin] = true;
}
}
}
}
}
int main()
{
Citire();
BellmanFord(1);
if(ok) fout << "Ciclu negativ!";
else
for(int i = 2; i <= N; ++i)
if(D[i] != inf)
fout << D[i] << ' ';
return 0;
}