Cod sursa(job #1377364)

Utilizator andreismara97Smarandoiu Andrei andreismara97 Data 5 martie 2015 21:24:35
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include<fstream>
#include<queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

#define N 50001
#define M 250001
#define INF 2147483647

int n, m;
int d[N], it[N];

int lst[N], urm[M], vf[M], cost[M], nvf=0;

queue <int> q;
bool ok[N];

int ciclu = 1;

void bellmanford(int x)
{
    for(int i=1; i<=n; i++)
        d[i] = INF;
    d[x] = 0;
    q.push(x);
    ok[x] = 1;

    while(!q.empty())
    {
        x = q.front();
        q.pop();
        ok[x] = 0;

        for(int i = lst[x]; i; i = urm[i])
        {
            int y = vf[i];
            int c = cost[i];

            if(d[x] + c < d[y])
            {
                d[y] = d[x] + c;

                if(!ok[y])
                {
                    ok[y] = 1;
                    q.push(y);

                    if(++it[y] > n)
                    {
                        out << "Ciclu negativ!\n";
                        ciclu = 0;
                        return;
                    }
                }
            }
        }
    }
}

void citire()
{
    int x, y, c;

    in >> n >> m;
    for(int i=1; i<=m; i++)
    {
        in >> x >> y >> c;

        vf[++nvf] = y;
        cost[nvf] = c;
        urm[nvf] = lst[x];
        lst[x] = nvf;
    }
}

void afisare()
{
    for(int i = 2; i <= n; i++)
        out << d[i] << ' ';
    out << '\n';
}

int main ()
{
    citire();
    bellmanford(1);
    if(ciclu)
        afisare();
    return 0;
}