Cod sursa(job #2152274)

Utilizator andreigeorge08Sandu Ciorba andreigeorge08 Data 5 martie 2018 13:23:26
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>
#define inf 10000000
#define pb push_back
#define st first
#define dr second
#define p push
#define f front

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

int n, m, viz[50005], frecv[50005], drum[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].pb({y, c});
    }
}

void Init()
{
    for(int i = 1; i <= n; i++)
        drum[i] = inf;
}

void Rez()
{
    int el;

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

    Init();
    drum[1] = 0;
    frecv[1] = 1;

    bool ciclu = 0;

    while(!q.empty() && !ciclu)
    {
        el = q.f();
        q.pop(); viz[el] = 0;

        for(auto i : L[el])
        {
            int nod = i.st;
            int cost = i.dr;
            if(drum[nod] > drum[el] + cost)
            {
                drum[nod] = drum[el] + cost;
                if(!viz[nod])
                {
                    viz[nod] = 1;
                    if(++frecv[nod] > n) ciclu = 1;
                    q.p(nod);
                }
            }
        }
    }

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