Cod sursa(job #2197806)

Utilizator andreigeorge08Sandu Ciorba andreigeorge08 Data 22 aprilie 2018 21:50:02
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>
#define inf 100000000
using namespace std;

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

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

void Citire()
{
    int x, y, c;
    fin >> n >> m;
    while(fin >> x >> y >> c)
    {
        L[x].push_back({y,c});
    }
}

void Dijkstra()
{
    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)
    {
        int 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();
    Dijkstra();
    return 0;
}