Cod sursa(job #3376910)

Utilizator AlphxByteStefan Alexandru AlphxByte Data 20 noiembrie 2026 10:40:18
Problema Algoritmul Bellman-Ford Scor 95
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.5 kb
#include <fstream>
#include <vector>
#include <queue>
#include <set>

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, short>> graph[N];
std::vector<int> distance;
std::vector<int> viz;
int n;

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

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

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

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

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

        viz[node]++;
        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(neighbour);
            }
        }
    }

    return false;
}
*/

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

    std::set<std::pair<int, int>> queue;

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

    while (!queue.empty())
    {
        int d = (*queue.begin()).first;
        int node = (*queue.begin()).second;
        queue.erase({d, node});

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

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

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

    return false;
}

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

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

    return 0;
}