Cod sursa(job #1656131)

Utilizator llalexandruLungu Alexandru Ioan llalexandru Data 18 martie 2016 19:48:31
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <fstream>
#include <queue>
#include <stdlib.h>
#define inf 1000000000
#define mp make_pair

using namespace std;

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

queue < int > Coada;

struct lista{int val, cost;};

int n, m, d[50005], neg, prez[50005], x, ori[50005];
lista *A[50005];

int main()
{
    int i, x, y, c;
    fin>>n>>m;
    for (i=1; i<=n; i++)
    {
        A[i] = (lista *) realloc (A[i], 2*sizeof(int));
        A[i][0].val = 0;
    }
    for (i=1; i<=m; i++)
    {
        fin>>x>>y>>c;
        A[x][0].val++;
        A[x] = (lista *) realloc (A[x], (A[x][0].val+1)*2*sizeof(int));
        A[x][A[x][0].val].val=y;
        A[x][A[x][0].val].cost=c;
    }
    for (i=1; i<=n; i++)
        d[i]=inf;
    d[1]=0;
    Coada.push(1);
    neg=0;
    int p;
    prez[1]=1;
    while (Coada.empty()==0 && neg==0)
    {
        x=Coada.front();
        Coada.pop();
        prez[x]=0;
        for (i=1; i<=A[x][0].val; i++)
        {
            p=A[x][i].val;
            c=A[x][i].cost;
            if (d[p]>d[x]+c)
            {
                d[p]=d[x]+c;
                if (prez[p]==0)
                {
                    if (ori[p] > n)
                        neg=1;
                    else
                    {
                        Coada.push(p);
                        prez[p]=1;
                        ori[p]++;
                    }
                }
            }
        }
    }
    if (neg==1)
        fout<<"Ciclu negativ!";
    else
        for (i=2; i<=n; i++)
            fout<<d[i]<<" ";
    return 0;
}