Cod sursa(job #1119342)

Utilizator muresan_bogdanMuresan Bogdan muresan_bogdan Data 24 februarie 2014 17:08:07
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include<iostream>
#include<fstream>
#include<queue>
#include<vector>
using namespace std;

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

const int INF = 1000000000;

struct cuplu {
    int id, cost;
};

struct nod {
    int cost;
    int cont;
    vector<cuplu> vecini;
};

bool operator<(const cuplu &a, const cuplu &b) {
    return a.cost > b.cost;
}

int n, m, i, a, b, c;
nod graf[50001];
priority_queue<cuplu> coada;

void dijkstra(int x) {
    int j;
    for(j = 0; j < graf[x].vecini.size(); j++) {
        cuplu vecin = graf[x].vecini[j];
        if(graf[x].cost + vecin.cost < graf[vecin.id].cost) {
            cuplu aux;
            aux.id = graf[x].vecini[j].id;
            aux.cost = graf[x].cost + graf[x].vecini[j].cost;
            coada.push(aux);
        }
    }
}

int main() {
    fin >> n >> m;
    cuplu aux;
    for(i = 0; i < m; i++) {
        fin >> a >> b >> c;
        aux.id = b;
        aux.cost = c;
        graf[a].vecini.push_back(aux);
    }
    for(i = 2; i <= n; i++) {
        graf[i].cost = INF;
    }
    aux.id = 1;
    aux.cost = 0;
    coada.push(aux);
    while(!coada.empty()) {
        aux = coada.top();
        coada.pop();
        graf[aux.id].cost = aux.cost;
        graf[aux.id].cont++;
        if(graf[aux.id].cont > n - 1) {
            fout << "Ciclu negativ!";
            return 0;
        }
        dijkstra(aux.id);
    }
    for(i = 2; i <= n; i++) {
        fout << graf[i].cost << ' ';
    }
    fin.close();
    fout.close();
    return 0;
}