Cod sursa(job #1881183)

Utilizator saba_alexSabadus Alex saba_alex Data 16 februarie 2017 11:19:57
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#define MAX 50005

using namespace std;

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

const int inf = 2147483647;
vector < pair < int, int > > G[MAX];
int n, m;
queue < int > Q;
int ap[MAX], dist[MAX];
bool ok;

int bellman(){

    int cm = m;
    while(!Q.empty()){
        int nod = Q.front();
        Q.pop();
        ap[nod]++;
        if(ap[nod] > cm){
            cout << "Ciclu negativ!";
            return 0;
        }
        for(auto it: G[nod]){
            if(dist[nod] + it.second < dist[it.first]){
                dist[it.first] = dist[nod] + it.second;
                Q.push(it.first);
            }
        }
    }
    return 1;
}

void afis(){

    if(!ok)
        return;
    for(int i = 2; i <= n; ++i)
        fout << dist[i] << ' ';
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; ++i){
        int x, y, z;
        fin >> x >> y >> z;
        G[x].push_back( make_pair(y, z) );
    }

    dist[1] = 0;
    Q.push(1);
    for(int i = 2; i <= n; ++i)
        dist[i] = inf;

    ok = bellman();

    afis();

    return 0;
}