Cod sursa(job #399752)

Utilizator newsabbathCaraman Sabina newsabbath Data 20 februarie 2010 23:34:03
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>

using namespace std;


const int inf = 10000;

struct graf{
    int vc, cost;
    graf *next;
} *L[250];
int d[300], n,m;


void add(graf *&prim, int vc, int c)
{
    graf *q= new graf;
    q -> vc = vc;
    q-> cost = c,
    q->next = prim;
    prim = q;
}


void citire()
{
    freopen("bellmanford.in", "r", stdin);
    scanf("%d%d", &n, &m);

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

    for(int i = 1; i<=m; i++)
    {
        int x, y,c;
        scanf("%d%d%d", &x, &y, &c);
        add(L[x], y,  c);
        if(x == 1)
            d[y] = c;
    }

}

void bellman()
{
    int ok;
    do {
    ok = 0;
    for(int k=1;k<=n;k++)
        for(graf *p = L[k];p;p= p->next)
            if( d[p->vc] > d[k] + p->cost)
                {
                    d[p->vc] = d[k] + p->cost /*pre[p->vc] = k*/;
                    ok = 1;
                }

    }while(ok == 0);

}

int circuit()
{
    for(int k=1;k<=n;k++)
        for(graf *p = L[k];p;p= p->next)
            if( d[p->vc] > d[k] + p->cost)
                    return 0;
    return 1;
}
/*
void afisare()
{

}*/
int main()
{
   freopen("bellmanford.out", "w", stdout);
    citire();
    bellman();
    if(circuit() == 0)
        printf("ciclu negativ!");
    else
        for(int i=2;i<=n;i++)
            printf("%d ",d[i]);
    return 0;
}