Cod sursa(job #3376916)

Utilizator AlphxByteStefan Alexandru AlphxByte Data 20 noiembrie 2026 10:49:37
Problema Algoritmul Bellman-Ford Scor 95
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 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.resize(n + 2);
    viz.resize(n + 2);

    for (int i = 0; i <= n + 1; ++i)
    {
        distance[i] = INF;
        viz[i] = 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].push_back({ y, c });
    }

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

    return 0;
}