Cod sursa(job #1729417)

Utilizator xSliveSergiu xSlive Data 14 iulie 2016 17:57:19
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <queue>
//#include <pair>
#define NMAX 50002
#define INF 100000
using namespace std;
//                      BELMAN FORD
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
vector< pair<int,int> > muchii[NMAX];//first = muchie second = cost
int cost[NMAX]={INF};
int freq[NMAX]={0};
int inCoada[NMAX]={0};
bool BelmanFord(int start,int n){
    queue<int> coada;
    coada.push(start);
    cost[start]=0;
    while(!coada.empty() ){
        int el = coada.front();
        coada.pop();
        inCoada[el]=0;
        for(vector< pair <int,int> >::iterator it=muchii[el].begin();it!=muchii[el].end();it++){
            if(cost[it->first] > cost[el] + it->second ){
                cost[it->first] = cost[el] + it->second;
                coada.push(it->first);
                if(!inCoada[it->first]){
                    freq[it->first]++;
                    if(freq[it->first] > n + 1)   return true;
                    inCoada[it->first]=1;
                }
            }
        }
    }
    return false;
}

void afisare(int start,int n){
    for(int i=1;i<=n;i++)
        if(i!=start){
            if(cost[i]==INF)
                g << 0 << " ";
            else
                g << cost[i] << " ";
        }
}

int main()
{
    int n,m,a,b,c;
    f >> n >> m;
    for(int i=0;i<m;i++){
        f >> a >> b >> c;
        muchii[a].push_back(make_pair(b,c));
    }
    bool ciclu = BelmanFord(1,n);
    if(ciclu) g << "Ciclu negativ!";
    else
        afisare(1,n);
    return 0;
}