Cod sursa(job #1378862)

Utilizator stefanlaculeanuLaculeanu Stefan stefanlaculeanu Data 6 martie 2015 14:51:50
Problema Algoritmul Bellman-Ford Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <iostream>
#include <fstream>
using namespace std;

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

int n, m, nr, lst[50005], urm[250005], vf[250005], inf=2000009, q[50005], d[50005], cost[250005], contor[50005], ca;
bool viz[50005], negativ;

void adauga( int x, int y, int z)
{
    vf[++nr]=y;
    cost[nr]=z;
    urm[nr]=lst[x];
    lst[x]=nr;

}

void bellmanford ( int x )
{
    int p=1, u=0, poz, y;
    q[++u]=x;
    viz[x]=true;
    contor[x]=1+contor[x];
    d[x]=0;
    while(p<=u)
    {
        x=q[p++];
        poz=lst[x];
        while(poz!=0)
        {
            y=vf[poz];
            ca=cost[poz];
            if(d[x]+ca<d[y])
            {
                d[y]=ca+d[x];
                if(!viz[y])
                {
                    q[++u]=y;
                    viz[y]=true;
                    contor[y]++;
                    if(contor[y]==n)
                    {
                        negativ=true;
                        break;
                    }
                }
            }
            poz=urm[poz];
        }
    }
}

int main()
{
    int a,b,c;
    in>>n>>m;
    for(int i=1;i<=m;i++)
    {
        in>>a>>b>>c;
        adauga(a, b, c);
    }
    for(int i=1;i<=n;i++)
    {
        d[i]=2000009;
    }
    bellmanford(1);
    if(negativ)
        out<<"Ciclu negativ!";
    else
    {
        for(int i=2;i<=n;i++)
        {
            out<<d[i]<<" ";
        }
    }
    return 0;
}