Cod sursa(job #3323774)

Utilizator PatrikKev75Szucs Patrik - Kevin PatrikKev75 Data 19 noiembrie 2025 20:15:54
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
// https://www.infoarena.ro/problema/bellmanford - Szücs Patrik - Kevin
#include <fstream>
#include <vector>
#include <climits>
#include <queue>

struct edge
{
    int to, price;
};

int main()
{
    int n, m;

    std::ifstream in("bellmanford.in");
    in >> n >> m;

    std::vector<std::vector<edge>> graf(n + 1);
    while (m--)
    {
        int x, y, w;
        in >> x >> y >> w;
        graf[x].push_back({y, w});
    }
    in.close();

    //------------------------------------------------------------------------------------
    // Bellmanford
    std::vector<int> dist(n + 1, INT_MAX), cnt(n + 1, 0);
    std::vector<bool> inQ(n + 1, false);
    dist[1] = 0;
    inQ[1] = true;

    std::queue<int> q;
    q.push(1);

    std::ofstream out("bellmanford.out");
    while (!q.empty())
    {
        int cur = q.front();
        inQ[cur] = false;
        q.pop();

        for (edge e : graf[cur])
        {
            int adrs = e.to, w = e.price;

            if (dist[cur] != INT_MAX && dist[cur] + w < dist[adrs])
            {
                dist[adrs] = dist[cur] + w;

                if (!inQ[adrs])
                {
                    inQ[adrs] = true;
                    q.push(adrs);

                    if (cnt[adrs] > n)
                    {
                        out << "Ciclu negativ!";
                        out.close();
                        return 0;
                    }
                    cnt[adrs]++;
                }
            }
        }
    }

    //------------------------------------------------------------------------------------

    for (int i = 2; i <= n; i++)
        out << dist[i] << ' ';

    out.close();
    return 0;
}