Cod sursa(job #3215819)

Utilizator PetraPetra Hedesiu Petra Data 15 martie 2024 13:11:42
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <bits/stdc++.h>

#define NMAX 50002

using namespace std;

ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");

struct muchie {
    int nod, cost;
};

int n, m, dist[NMAX], cnt[NMAX];
vector<muchie> G[NMAX];
bitset<NMAX> viz;
queue<int> q;

int bellmanford(int start)
{
    memset(dist, 0x3f, sizeof(dist));
    dist[start] = 0;

    q.push(start);
    viz[start] = true;
    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        viz[nod] = false;

        for (auto vec : G[nod])
        {
            if (dist[vec.nod] > dist[nod] + vec.cost)
            {
                dist[vec.nod] = dist[nod] + vec.cost;
                if (!viz[vec.nod])
                {
                    q.push(vec.nod);
                    viz[vec.nod] = true;

                    cnt[vec.nod]++;
                    if (cnt[vec.nod] > n)
                        return false;
                }
            }
        }
    }
    return true;
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        G[x].push_back({y, c});
    }

    bool ok = bellmanford(1);
    if (ok)
    {
        for (int i = 2; i <= n; i++)
            fout << dist[i] << " ";
    }
    else fout << "Ciclu negativ!";

    return 0;
}