Cod sursa(job #1370847)

Utilizator FapFapAdriana FapFap Data 3 martie 2015 17:37:28
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <queue>
#include <fstream>
#define nmax 50005
#define inf (1<<30)
#define value first
#define node second
using namespace std;

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

vector< pair<int, int> > v[nmax];
queue <int> q;

int number_of_nodes, number_of_edges;
int previous[nmax], cycle[nmax], best[nmax];

void bellman(){
    for(int i=2; i<=number_of_nodes; i++)   best[i]= inf;
    q.push(1);
    while(!q.empty()){
        int current= q.front();
        q.pop();
        for(int i=0; i<v[current].size(); i++){
            int neigh= v[current][i].node;
            int neigh_value= v[current][i].value;
            if(best[neigh] > best[current]+ neigh_value){
                best[neigh]= best[current]+ neigh_value;
                cycle[neigh]++;
                previous[neigh]= current;
                q.push(neigh);
                if(cycle[neigh] > number_of_nodes){
                    fout << "Ciclu negativ!\n";
                    return;
                }
            }
        }
    }
    for(int i=2; i<=number_of_nodes; i++)
        if(best[i]==inf)    fout << 0 << " ";
    else    fout << best[i] << " ";
}

int main(){
    int x, y, w;
    fin >> number_of_nodes >> number_of_edges;
    for(int i=1; i<=number_of_edges; i++){
        fin >> x >> y >> w;
        v[x].push_back(make_pair(w, y));
    }
    bellman();
    return 0;
}