Cod sursa(job #3376861)

Utilizator AlphxByteStefan Alexandru AlphxByte Data 20 noiembrie 2026 09:06:45
Problema Algoritmul Bellman-Ford Scor 55
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.13 kb
#include <fstream>
#include <vector>
#include <queue>

const std::string FILE_NAME = "bellmanford";
const int N = 5e4 + 1;
const int INF = 0x3F3F3F3F;

std::ifstream fin(FILE_NAME + ".in");
std::ofstream fout(FILE_NAME + ".out");

std::vector<std::pair<int, int>> graph[N];
std::vector<int> distance;
std::vector<bool> viz;
int n;

bool BellmanFord(int start_node)
{
    distance = std::vector<int>(n + 1, INF);
    viz = std::vector<bool>(n + 1, false);

    std::priority_queue<std::pair<int, int>,
        std::vector<std::pair<int, int>>,
        std::greater<std::pair<int, int>>> queue;

    queue.push({ 0, start_node });
    distance[start_node] = 0;
    viz[start_node] = true;

    while (!queue.empty())
    {
        int node = queue.top().second;
        int d = queue.top().first;
        queue.pop();

        if (viz[node] && distance[node] < 0)
            return true;

        viz[node] = true;
        for (const auto& edge : graph[node])
        {
            int neighbour = edge.first;
            int c = edge.second;

            if (distance[neighbour] > distance[node] + c)
            {
                distance[neighbour] = distance[node] + c;
                queue.push({ distance[neighbour], neighbour });
            }
        }
    }

    return false;
}

/*
bool BellmanFord(int start_node)
{
    for (int i = 1; i <= n; i++)
        distance[i] = INFINIT;

    distance[start_node] = 0;
    for (int i = 1; i < n; i++)
        for (const auto& edge : edges)
            if (distance[edge.y] > distance[edge.x] + edge.cost)
                distance[edge.y] = distance[edge.x] + edge.cost;

    for (const auto& edge : edges)
        if (distance[edge.y] > distance[edge.x] + edge.cost)
            return true;

    return false;
}
*/

int main()
{
    int m;
    fin >> n >> m;
    while (m--)
    {
        int x, y, c;
        fin >> x >> y >> c;
        graph[x].push_back({ y, c });
    }

    if (BellmanFord(1))
        fout << "Ciclu negativ!";
    else
        for (int i = 2; i <= n; i++)
            fout << distance[i] << ' ';

    return 0;
}