Cod sursa(job #2172911)

Utilizator razvan99hHorhat Razvan razvan99h Data 15 martie 2018 18:56:58
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define DM 50005
#define INF 0x3f3f3f3f
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

int n, m, dist[DM], viz[DM], a, b ,c;
queue <int> q;
vector < pair<int, int> > g[DM];

void bellmanford()
{
    for(int i = 2; i <= n; i++)
        dist[i] = INF;
    q.push(1);
    while(!q.empty())
    {
        int nod = q.front();
        q.pop();
        for(auto it : g[nod])
            if(dist[nod] + it.second < dist[it.first])
            {
                dist[it.first] = dist[nod] + it.second ;
                q.push(it.first);
                viz[it.first]++;
                if(viz[it.first] > n)
                {
                    fout << "Ciclu negativ!";
                    return;
                }
            }
    }
    for(int i = 2; i <= n; i++)
        fout << dist[i] << ' ';
}
int main ()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> a >> b >> c;
        g[a].push_back({b, c});
    }
    bellmanford();
    return 0;
}