Pagini recente » Cod sursa (job #1681172) | Cod sursa (job #2985969) | Cod sursa (job #1749181) | Profil Iordache_Ana | Cod sursa (job #2683564)
#include <fstream>
#include <queue>
#include <vector>
constexpr auto max_n = 50005;
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
vector<pair<int, int>> graph[max_n];
bool is_in_queue[max_n];
int min_dist[max_n];
int cycle_times[max_n];
int main()
{
fin >> n >> m;
for (auto i = 0; i < m; i++)
{
int a, b, c;
fin >> a >> b >> c;
graph[a].push_back(make_pair(b, c));
}
for (auto i = 1; i <= n; i++)
min_dist[i] = 0x3f3f3f3f;
queue<int> nodes_queue;
nodes_queue.push(1);
min_dist[1] = 0;
is_in_queue[1] = true;
bool negative_cycle = false;
while (!nodes_queue.empty() && !negative_cycle)
{
const auto crt_node = nodes_queue.front();
nodes_queue.pop();
is_in_queue[crt_node] = false;
for (auto &neigh : graph[crt_node])
{
if (!is_in_queue[neigh.first])
{
if (min_dist[neigh.first] > min_dist[crt_node] + neigh.second)
{
if (cycle_times[neigh.first] > n)
negative_cycle = true;
else
{
min_dist[neigh.first] = min_dist[crt_node] + neigh.second;
cycle_times[neigh.first]++;
is_in_queue[neigh.first] = true;
nodes_queue.push(neigh.first);
}
}
}
}
}
if (negative_cycle)
fout << "Ciclu negativ!";
else
for (auto i = 2; i <= n; i++)
fout << min_dist[i] << " ";
return 0;
}