Cod sursa(job #2152281)

Utilizator andreigeorge08Sandu Ciorba andreigeorge08 Data 5 martie 2018 13:28:20
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>
#define inf 100000000

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

int n, m, frecv[50005], drum[50005];
bool viz[50005];
vector <pair<int, int> > L[50005];
queue <int> q;

void Citire()
{
    int x, y, c;

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

void Rez()
{
    int el;

    q.push(1);
    viz[1] = 1;

    for(int i = 1; i <= n; i++)
        drum[i] = inf;

    drum[1] = 0;
    frecv[1] = 1;

    bool ciclu = 0;

    while(!q.empty() && !ciclu)
    {
        el = q.front();
        q.pop();

        viz[el] = 0;
        for(auto i : L[el])
        {
            int nod = i.first;
            int cost = i.second;

            if(drum[nod] > drum[el] + cost)
            {
                drum[nod] = drum[el] + cost;

                if(!viz[nod])
                {
                    viz[nod] = 1;
                    if(++frecv[nod] > n) ciclu = 1;
                    q.push(nod);
                }
            }
        }
    }

    if(ciclu)
        fout << "Ciclu negativ!\n";
    else for(int i = 2; i <= n; i++)
            fout << drum[i] << " ";
}
int main()
{
    Citire();
    Rez();
    return 0;
}