Pagini recente » Diferente pentru implica-te/arhiva-educationala intre reviziile 220 si 223 | Cod sursa (job #3293246) | Cod sursa (job #378876) | Diferente pentru implica-te/arhiva-educationala intre reviziile 176 si 223 | Cod sursa (job #3293399)
#include <bits/stdc++.h>
using namespace std;
vector <pair <int, int>> graf[50005];
queue <int> solve;
int distanta[50005];
int nrNoduri[50005];
int main()
{
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
int n, m;
fin >> n >> m;
for (int i = 1; i<=m; ++i)
{
int x, y, cost;
fin >> x >> y >> cost;
graf[x].push_back ({y, cost});
//graf[y].push_back ({x, cost});
}
for (int i = 2; i<=n; ++i)
distanta[i] = 1<<30;
nrNoduri[1] = 1;
distanta[1] = 0;
solve.push(1);
while (!solve.empty())
{
int nod = solve.front();
solve.pop();
if (nrNoduri[nod]>n)
{
// cand drumul de lun min contine mai mult de N noduri, garantat exista un ciclu in el
// singurul motiv pentru care as avea un ciclu pe un drum MINIM este daca ciclul este negativ
fout << "Ciclu negativ!";
return 0;
}
for (auto x:graf[nod])
{
if (distanta[x.first] > distanta[nod]+x.second)
{
nrNoduri[x.first] = nrNoduri[nod] + 1;
distanta[x.first] = distanta[nod]+x.second;
solve.push(x.first);
}
}
}
for (int i = 2; i<=n; ++i)
fout << distanta[i] << " ";
return 0;
}