Pagini recente » Borderou de evaluare (job #1569862) | Cod sursa (job #2507738) | Cod sursa (job #724551) | Cod sursa (job #2349280) | Cod sursa (job #2772594)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <climits>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n, m;
vector<pair<int, int>>adiacenta[50001];
queue<int>q;
int costuri[50001];
int entered_queue[50001];
int main()
{
f >> n >> m;
for (int i = 1; i <= m; i++)
{
int nr1, nr2, cost;
f >> nr1 >> nr2 >> cost;
adiacenta[nr1].push_back({ nr2,cost });
}
for (int i = 1; i <= n; i++)
{
costuri[i] = INT_MAX;
}
costuri[1] = 1;
entered_queue[1] = 1;
q.push(1);
while (!q.empty())
{
int nod_curent = q.front();
q.pop();
for (auto x : adiacenta[nod_curent])
{
if (costuri[x.first] > costuri[nod_curent] + x.second)
{
costuri[x.first] = costuri[nod_curent] + x.second;
q.push(x.first);
entered_queue[x.first]++;
}
if (entered_queue[x.first] > n)
{
g << "Ciclu negativ!";
return 0;
}
}
}
for (int i = 2; i <= n; i++)
{
if (costuri[i] == INT_MAX)
{
g << "0 ";
}
else
g << costuri[i] - 1 << " ";
}
}