Pagini recente » Cod sursa (job #712157) | Cod sursa (job #2103874) | Cod sursa (job #1221669) | Cod sursa (job #720264) | Cod sursa (job #2148432)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
const int Nmax = 50005;
const int inf = (1 << 30);
queue < int > Q;
int n , m , dist[Nmax] , freq[Nmax];
vector < pair < int , int > > L[Nmax];
bool viz[Nmax];
int main()
{
int x , y , c;
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;
Q . push(1);
while(! Q . empty() && !cycle)
{
x = Q . front();
Q . pop();
viz[x] = false;
for(auto w : L[x])
if(dist[w . first] > dist[x] + w . second)
{
dist[w . first] = dist[x] + w . second;
if(!viz[w . first])
{
viz[w . first] = true;
++freq[w . first];
if(freq[w . first] > n)
cycle = true;
Q . push(w . first);
}
}
}
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;
}