Cod sursa(job #2837456)

Utilizator VladPislaruPislaru Vlad Rares VladPislaru Data 22 ianuarie 2022 10:50:06
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <bits/stdc++.h>

using namespace std;

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


vector <pair <int ,int> > h[50005];
int n, d[50005], m, viz[50005];
int cnt[50005]; /// numar de cate ori am pus nodul i in coada
queue <int> q;

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

void BellmanFord()
{
    bool ciclu_negativ = false;
    int i;
    /// initializari:
    for (i = 1; i <= n; i++)
        d[i] = 2e9;
    d[1] = 0;
    q.push(1);
    viz[1] = 1;
    cnt[1]++;
    while (!q.empty() && !ciclu_negativ)
    {
        int x = q.front();
        q.pop();
        viz[x] = 0;
        for (auto i : h[x])
        {
            int nod = i.first;
            int c = i.second;
            if (d[nod] > d[x] + c)
            {
                d[nod] = d[x] + c;
                if (viz[nod] == 0)
                {
                    cnt[nod]++;
                    if (cnt[nod] > n)
                        ciclu_negativ = true;
                    else
                    {
                        q.push(nod);
                        viz[nod] = 1;
                    }
                }
            }
        }
    }
    if (ciclu_negativ)
        fout << "Ciclu negativ!";
    else for (int i = 2; i <= n; i++)
        fout << d[i] << " ";
    fout << "\n";
}

int main()
{
    Citire();
    BellmanFord();
    fout.close();
    return 0;
}