Cod sursa(job #1135546)

Utilizator andreiblaj17Andrei Blaj andreiblaj17 Data 7 martie 2014 23:46:12
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <queue>
using namespace std;

#define nmax 50001
#define inf (1<<30)
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

int n,m,a,b,x,i;
int cost[nmax],viz_nod[nmax];
bool viz[nmax];
vector < pair <int, int> > vecin[nmax];
set < pair <int , int> > S;

void bellmanford(){
    
    for (i=2; i<=n; i++) cost[i]=inf;
    
    S.insert(make_pair(0, 1));
    
    while (!S.empty()){
        int nod=(*S.begin()).second;
        int MIN=(*S.begin()).first;
        
        S.erase(S.begin());
        
        viz[nod]=0;
        
        for (i=0; i<vecin[nod].size(); i++){
            int vc=vecin[nod][i].first;
            int c=vecin[nod][i].second;
            
            if (!viz[vc]) viz_nod[vc]++, viz[vc]=1;
            
            if (viz_nod[vc]>n){
                out << "Ciclu negativ!" << "\n";
                return;
            }
            
            if (cost[vc]>MIN+c){
                cost[vc]=MIN+c;
                S.insert(make_pair(cost[vc], vc));
            }
            
        }
        
    }
    
    for (i=2; i<=n; i++) out << cost[i] << " ";
    
}

int main(){
    
    in >> n >> m;
    
    for (i=1; i<=m; i++)
        in >> a >> b >> x,
        vecin[a].push_back(make_pair(b, x));
    
    bellmanford();
    
    return 0;
}