Pagini recente » Istoria paginii runda/runda_0/clasament | Cod sursa (job #1442210) | Cod sursa (job #66193) | Statistici Horatiu Cheval (horatiucheval) | Cod sursa (job #2377132)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
const int Nmax = 50005;
const int oo = (1 << 30);
struct Graf
{
int nod, cost;
inline bool operator < (const Graf &A) const
{
return cost > A.cost;
}
};
priority_queue <Graf> Q;
vector < pair < int, int > > L[Nmax];
int n, m;
int dist[Nmax], freq[Nmax];
bool viz[Nmax];
bool cycle;
void Read()
{
int i;
int x, y, c;
fin >> n >> m;
for(i = 1 ; i <= m ; i++)
{
fin >> x >> y >> c;
L[x] . push_back({y, c});
}
fin.close();
}
void Init()
{
int i;
for(i = 1 ; i <= n ; i++)
dist[i] = oo;
}
void BellmanFord()
{
Graf w, w1;
cycle = false;
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 k : L[w.nod])
if(dist[k.first] > dist[w.nod] + k.second)
{
dist[k.first] = dist[w.nod] + k.second;
++freq[k.first];
if(freq[k.first] > n) cycle = true;
if(!viz[k.first])
{
viz[k.first] = true;
w1 = {k.first, dist[k.first]};
Q.push(w1);
}
}
}
}
void Write()
{
int i;
if(cycle)
fout << "Ciclu negativ!\n";
else
{
for(i = 2 ; i <= n ; i++)
fout << dist[i] << " ";
fout << "\n";
}
fout.close();
}
int main()
{
Read();
Init();
BellmanFord();
Write();
return 0;
}