Pagini recente » Cod sursa (job #770463) | Cod sursa (job #2786935) | Cod sursa (job #3295355)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int NMAX = 50002;
vector <pair <int, int>> a[NMAX];
queue <int> coada;
int distante[NMAX], nr_noduri[NMAX];
bool in_coada[NMAX];
int n, m;
void bellman_ford(int sursa)
{
for(int i=2; i<=n; ++i)
{
distante[i] = 1e9;
}
nr_noduri[sursa] = 1;
distante[1] = 0;
coada.push(1);
in_coada[1] = true;
while(!coada.empty())
{
int nod = coada.front();
coada.pop();
in_coada[nod] = false;
if(nr_noduri[nod] > n)
{
fout << "Ciclu negativ!";
exit(0);
}
for(auto x : a[nod])
{
if(distante[x.first] > distante[nod] + x.second)
{
nr_noduri[x.first] = nr_noduri[nod] + 1;
distante[x.first] = distante[nod] + x.second;
if(in_coada[x.first] == 0)
{
coada.push(x.first);
in_coada[x.first] = true;
}
}
}
}
}
int main()
{
fin >> n >> m;
for(int i=1; i<=m; ++i)
{
int x, y, cost;
fin >> x >> y >> cost;
a[x].push_back({y, cost});
}
int sursa = 1;
bellman_ford(sursa);
for(int i=2; i<=n; ++i)
fout << distante[i] << " ";
return 0;
}