Cod sursa(job #1314600)

Utilizator AnesthesicChereches Sergiu Alexandru Anesthesic Data 11 ianuarie 2015 23:44:58
Problema Algoritmul Bellman-Ford Scor 85
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
#define nmax 50001
#define weight first
#define node second
#define inf (1<<30)
using namespace std;

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

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

void bellman_ford(int n, int best[nmax], int cycle[nmax], bool cycle_inf){
    for(int i=2; i<=n; i++) best[i]= inf;
    q.push(1);
    while(!q.empty()){
        int current = q.front();
        for(int i=0; i<v[current].size(); i++)
            if(best[v[current][i].node] > best[current] + v[current][i].weight){
                best[v[current][i].node]= best[current] + v[current][i].weight;
                q.push(v[current][i].node);
                cycle[v[current][i].node]++;
                if(cycle[v[current][i].node]>n){
                    cycle_inf=true;
                    break;
                }
            }
        if(cycle_inf) break;
        q.pop();
    }
    if(cycle_inf) fout << "Ciclu negativ!\n";
    else    for(int i=2; i<=n; i++) fout << best[i] << " ";

}

int main(){
    int x, y, w, i, n, m;
    int best[nmax], cycle[nmax];
    bool cycle_inf = false;

    fin >> n >> m;
    for(i=1; i<=m; i++){
        fin >> x >> y >> w;
        v[x].push_back(make_pair(w, y));
    }
    bellman_ford(n, best, cycle, cycle_inf);
    return 0;
}