Cod sursa(job #2152681)

Utilizator andrei.gramescuAndrei Gramescu andrei.gramescu Data 5 martie 2018 18:46:27
Problema Algoritmul Bellman-Ford Scor 15
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <cstdio>
#include <vector>
using namespace std;
#define NMAX 50005
#define MMAX 250005
#define INFINIT 1000000000

struct EDGE{
    int x, y, cost;
};

int main(){

    bool cicluNeg = false;
    EDGE temp;
    vector<EDGE> edges;
    int n, m, d[NMAX];
    int a, b, c, i, j;
    FILE *fin, *fout;
    fin = fopen("bellmanford.in", "r");
    fout = fopen("bellmanford.out", "w");

    fscanf(fin, "%d %d", &n, &m);
    for(i=1; i<=m; i++){
        fscanf(fin, "%d %d %d", &a, &b, &c);
        temp.x = a;
        temp.y = b;
        temp.cost = c;
        edges.push_back(temp);
    }

    for(i=2; i<=n; i++)
        d[i] = INFINIT;
    d[1] = 0;

    for(i=1; i<=n-1; i++){
        for(j=0; j<(int) edges.size(); j++){
            if(d[ edges[j].y ] > d[ edges[j].x ] + edges[j].cost){
                d[ edges[j].y ] = d[ edges[j].x ] + edges[j].cost;
            }
        }
    }

    for(j=0; j<m; j++){
            if(d[ edges[j].y ] > d[ edges[j].x ] + edges[j].cost){
                cicluNeg = true;
                break;
            }
    }

    if(cicluNeg)
        fprintf(fout, "Ciclu negativ!");

    for(i=2; i<=n; i++)
        fprintf(fout, "%d ", d[i]);

    return 0;
}