Cod sursa(job #1341431)

Utilizator daniel.grosuDaniel Grosu daniel.grosu Data 12 februarie 2015 18:56:09
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
/* Bellman-ford implementation */
#include <fstream>
#include <vector>
#define pb push_back
#define VMAX 1000
#define infinite 100000000
using namespace std;

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

int n,m,s;

struct edge{
    int w;
    int to;
    edge *next;
};

edge* G[VMAX];
int dist[VMAX];
int pred[VMAX];

void add(struct edge **l, int n, int w)
{
    edge *p = new edge;
    p->to=n;
    p->w=w;
    p->next = *l;
    *l=p;
    fout<<"add "<<n<<"\n";
}

void bellman()
{
    
    // initializam graph-ul
    for(int i=1; i<=n; i++)
        dist[i]=infinite;
    dist[s]=0;
    
    // relaxam de |u-1| ori graph-ul
    for(int u=1; u<=n-1; u++)
        for(edge *p=G[u]; p; p=p->next){
            if(dist[u] + p->w < dist[p->to])
                dist[p->to] = dist[u] + p->w, pred[p->to]=u;
            fout<<p->to<<" - to \n";
        }

    
    // verificam ciclurile negative
    for(int u=1; u<=n-1; u++)
        for(edge *p=G[u]; p; p=p->next)
            if(dist[u] + p->w < dist[p->to])
                fout<<"Ciclu negativ!";
}

void read()
{
    fin>>n>>m>>s;
    for(int i=1; i<=m; ++i)
    {
        int a,b,c;
        fin>>a>>b>>c;
        add(&G[a], b, c);
    }
}

int main()
{
    read();
    bellman();
    for(int i=2; i<=n; ++i)
        fout<<dist[i]<<" ";
    
    return 0;
}