Pagini recente » Cod sursa (job #2767) | Cod sursa (job #3031389) | Cod sursa (job #2314353) | Cod sursa (job #2186838) | Cod sursa (job #2152809)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
const int Nmax = 50005;
const int inf = (1 << 30);
struct Graf
{
int nod , cost;
bool operator < (const Graf & e ) const
{
return cost > e . cost;
}
};
priority_queue <Graf> Q;
int n, m, dist[Nmax], freq[Nmax];
vector < pair < int, int > > L[Nmax];
bool viz[Nmax];
int main()
{
int x, y, c;
Graf w , w1;
bool cycle = false;
fin >> n >> m;
for(int i = 1 ; i <= m ; i++)
{
fin >> x >> y >> c;
L[x] . push_back({y, c});
}
for(int i = 1 ; i <= n ; i++)
dist[i] = inf;
dist[1] = 0;
viz[1] = true;
freq[1] = 1;
w = {1 , 0};
Q . push(w);
while(! Q . empty() && !cycle)
{
w = Q . top();
Q . pop();
viz[w . nod] = false;
for(auto pas : L[w . nod])
if(dist[pas . first] > dist[w . nod] + pas . second)
{
dist[pas . first] = dist[w . nod] + pas . second;
++freq[pas . first];
if(freq[pas . first] > n)
cycle = true;
if(!viz[pas . first])
{
viz[pas . first] = true;
w1 = {pas . first , dist[pas . first]};
Q . push(w1);
}
}
}
if(cycle)
fout << "Ciclu negativ!\n";
else
{
for(int i = 2 ; i <= n ; i++)
fout << dist[i] << " ";
fout << "\n";
}
fin.close();
fout.close();
return 0;
}