Cod sursa(job #2329369)

Utilizator FredyLup Lucia Fredy Data 26 ianuarie 2019 17:07:08
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

#define inf 2e9
#define lim 50010
int n,m,nod;
vector <pair <int,int>> G[lim];
int viz[lim],path[lim];
queue <int> q;

int main()
{
    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=2; i<=n; i++)    path[i] = inf;
    path[1] = 0;
    q.push(1);

    while (!q.empty())
    {
        nod = q.front();
        q.pop();
        viz[nod]++;
        if (viz[nod] > n)
        {
            fout<<"Ciclu negativ!";
            return 0;
        }
        for (auto it:G[nod])
            if (path[it.first] > path[nod] + it.second)
            {
                path[it.first] = path[nod] + it.second;
                q.push (it.first);
            }
    }

    for (int i=2; i<=n; i++)
        fout<<path[i]<<' ';

    fin.close();
    fout.close();
    return 0;
}