Cod sursa(job #2859215)

Utilizator razvanalexrotaruRazvan Alexandru Rotaru razvanalexrotaru Data 28 februarie 2022 23:57:24
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>
#define INF 1000000004
#define NMAX 50004

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

int n, m, start;
int dp[NMAX], nr[NMAX];
vector < pair <int, int> > G[NMAX];
queue <int> C;

void citire();
bool bellman_ford(); /// 0 daca exista circuite de cost negativ si 1 altfel

int main()
{
    citire();
    if (bellman_ford())
    {
        for (int i = 2; i <= n; i++)
        {
            if (dp[i] == INF)
                fout << 0 << ' ';
            else
                fout << dp[i] << ' ';
        }
    }
    else
        fout << "Ciclu negativ!";
    return 0;
}

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

bool bellman_ford()
{
    ///initializez coada cu varful de start
    C.push(1);
    nr[1] = 1;
    dp[1] = 0;

    while (!C.empty())
    {
        int x = C.front();
        C.pop();
        ///parcurg lista de adiacenta a lui x
        for (int i = 0; i < G[x].size(); i++)
        {
            int vf = G[x][i].first;
            int cost = G[x][i].second;
            if (dp[vf] > dp[x] + cost)
            {
                dp[vf] = dp[x] + cost;
                nr[vf]++;
                C.push(vf);
                if (nr[vf] == n)
                    return 0;
            }
        }
    }
    return 1;
}