Cod sursa(job #2197798)

Utilizator andreigeorge08Sandu Ciorba andreigeorge08 Data 22 aprilie 2018 21:40:01
Problema Algoritmul Bellman-Ford Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 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];
priority_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);
    for(int i = 1; i <= n; i++)
        drum[i] = inf;
    drum[1] = 0;
    viz[1] = true;

    bool ciclu = false;
    while(!q.empty() && ciclu == false)
    {
        int el = q.top();
        q.pop();

        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 = true;
                    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;
}