Cod sursa(job #2172821)

Utilizator SnokySlivilescu Vlad Snoky Data 15 martie 2018 18:07:51
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;

#define NMax 50005
#define oo (1 << 30)

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

int n, m, ap[NMax], D[NMax];
vector < pair < int, int> > G[NMax];
queue <int> q;

int bellmanford(int start)
{
    for(int i = 1; i <= n; i++)
        D[i] = oo;
    D[start] = 0;
    q.push(start);
    while(!q.empty())
    {
        int nod = q.front();
        q.pop();
        ap[nod]++;
        if(ap[nod] > n) return 0;
        for(int i = 0; i < G[nod].size(); i++)
        {
            int v = G[nod][i].first;
            int c = G[nod][i].second;
            if(D[nod] + c < D[v])
            {
                D[v] = D[nod] + c;
                q.push(v);
            }
        }
    }
    return 1;
}

int main()

{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        G[x].push_back({y, c});
    }
    if(!bellmanford(1))
        fout << "Ciclu negativ!";
    else
    {
        for(int i = 2; i <= n; i++)
            fout << D[i] << " ";
    }
}