Cod sursa(job #456207)

Utilizator carbonixVictor Carbune carbonix Data 14 mai 2010 23:20:42
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
/*
 * =====================================================================================
 *
 *       Filename:  dijkstra.cpp
 *
 *    Description:  
 *
 *         Author:  Victor Carbune ([email protected])
 *	     Info:  Grupa 325, Seria CA
 *
 * =====================================================================================
 */
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>

#define INF 1000000

using namespace std;

typedef struct _edge
{
    int x, y, cost;
} edge;

vector< pair<int, int> > *graf;
int n, m, *d;

ifstream in("bellmanford.in", ifstream::in);
ofstream out("bellmanford.out", ofstream::out);


void read_data()
{
    int x, y, cost;
    
    in >> n >> m;

    graf = new vector< pair<int, int> >[n];

    for (int i = 0; i < m; i++) {
        in >> x >> y >> cost;
        x--, y--;
        graf[x].push_back(make_pair(y, cost));
    }
}

int bellmanford(int s)
{
    d = new int[n];
    
    for (int i = 0; i < n; i++)
        d[i] = INF;

    d[s] = 0;

    for (int i = 0; i < n; i++ ) {
        for (int j = 0; j < graf[i].size(); j++ ) {
            if (d[graf[i][j].first] > d[i] + graf[i][j].second) {
                d[graf[i][j].first] = d[i] + graf[i][j].second;
            }
        }
    }

    
    for (int i = 0; i < n; i++ ) {
        for (int j = 0; j < graf[i].size(); j++ ) {
            if (d[graf[i][j].first] > d[i] + graf[i][j].second) {
                return 1;
            }
        }
    }
    return 0;
}




int main() {
    read_data();

    if (bellmanford(0)) {
        printf("Ciclu negativ!\n");
    } else {
        for (int i = 1; i < n; i++)
            out << (d[i] == INF ? 0:d[i]) << " ";
        out << endl;
    }

    return 0;
}