Cod sursa(job #1366877)

Utilizator somuBanil Ardej somu Data 1 martie 2015 14:23:03
Problema Algoritmul Bellman-Ford Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#define inf 1<<30
#define nmax 50005

using namespace std;

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

int n, m;
int cost[nmax], used[nmax];
bool ok = true;
vector < pair <int, int> > G[nmax];
set < pair<int, int> > S;

void bellmanFord(int nod) {
    cost[nod] = 0;
    S.insert(make_pair(nod, cost[nod]));
    for (; S.size();) {
        int nodCurent = (*S.begin()).first;
        int costCurent = (*S.begin()).second;
        S.erase(S.begin());
        for (int i = 0; i < G[nodCurent].size(); i++) {
            int vecinCurent = G[nodCurent][i].first;
            int costVecin = G[nodCurent][i].second;
            
            if (cost[vecinCurent] > costCurent + costVecin) {
                cost[vecinCurent] = costCurent + costVecin;
                used[vecinCurent]++;
                S.insert(make_pair(vecinCurent, cost[vecinCurent]));
            }
            
            if (used[vecinCurent] > n) {
                ok = false;
                fout << "Ciclu negativ!\n";
                return;
            }
            
        }
    }
}

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));
    }
    
    for (int i = 1; i <= n; i++)
        cost[i] = inf;
    
    bellmanFord(1);
    
    if (ok)
        for (int i = 2; i <= n; i++)
            cost[i] == inf ? fout << 0 << " " : fout << cost[i] << " ";
    
    fin.close();
    fout.close();
    
    return 0;
}