Pagini recente » Cod sursa (job #1013658) | Cod sursa (job #451308) | Cod sursa (job #2598928) | Cod sursa (job #1849613) | Cod sursa (job #2772592)
#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<pair<int,int>>q;
int costuri[50000];
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,1 });
while (!q.empty())
{
int nod_curent = q.front().first;
int cost_curent = q.front().second;
q.pop();
for (auto x : adiacenta[nod_curent])
{
if (costuri[x.first] > cost_curent + x.second)
{
costuri[x.first] = cost_curent + x.second;
q.push({ x.first,costuri[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 << " ";
}
}