Pagini recente » Cod sursa (job #84379) | Cod sursa (job #2321274) | Cod sursa (job #2374185) | Cod sursa (job #632661) | Cod sursa (job #2722071)
#include <fstream>
#include <vector>
#include <climits>
#include <queue>
using namespace std;
const int NMAX = 50000;
vector<pair<int, int>> graf[1 + NMAX];
int costuri[1 + NMAX];
queue<int> q;
bool inCoada[1 + NMAX];
int frecv[1 + NMAX];
int main()
{
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int n, m;
in >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, c;
in >> x >> y >> c;
graf[x].emplace_back(make_pair(y, c));
}
costuri[1] = 0;
for (int i = 2; i <= n; i++)
{
costuri[i] = INT_MAX;
}
q.emplace(1);
inCoada[1] = true;
while (!q.empty())
{
int nod = q.front();
q.pop();
inCoada[nod] = false;
for (int i = 0; i < graf[nod].size(); i++)
{
if (costuri[graf[nod][i].first] > costuri[nod] + graf[nod][i].second)
{
costuri[graf[nod][i].first] = costuri[nod] + graf[nod][i].second;
frecv[graf[nod][i].first]++;
if (frecv[graf[nod][i].first] == n)
{
out << "Ciclu negativ!" << '\n';
return 0;
}
if (!inCoada[graf[nod][i].first])
{
q.emplace(graf[nod][i].first);
inCoada[graf[nod][i].first] = true;
}
}
}
}
for (int i = 2; i <= n; i++)
{
out << costuri[i] << ' ';
}
return 0;
}