Cod sursa(job #862575)

Utilizator cristian.ion94Ion Cristian cristian.ion94 Data 22 ianuarie 2013 19:47:40
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include <fstream>
#define DMAX 50005
#define INFINIT 100000000
using namespace std;

ofstream fout("bellmanford.out");

struct Node
{
    int next_node;
    double cost;
};

Node ** C;

int * Cmin;
int * count;
int * nrpus;
int n, m;
bool optim;

void citire();
void BellmanFord();
void afisare();

int main()
{
    citire();
    BellmanFord();
    afisare();
    fout.close();
    return 0;
}

void citire()
{
    ifstream fin("bellmanford.in");
    int i,x,y,c;

    fin >> n >> m;

    Cmin = new int[n+1];
    count = new int[n+1];
    nrpus = new int[n+1];

    C = new Node*[n+1];
    for(i = 1; i <= n; i++)
    {
        C[i] = new Node[n+1];
        count[i] = 0;
        nrpus[i] = 0;
    }



    for(i = 1; i <= m; i++)
    {
        fin >> x >> y >> c;

        count[x]++;
        C[x][count[x]].next_node = y;
        C[x][count[x]].cost = c;
    }

    fin.close();
}

void BellmanFord()
{
    int inc=0, sf=-1;
    int i;
    int * Q = new int[n+1];

    for(i = 1; i<= n; i++)
    {
        Q[++sf] = i; nrpus[i]++;
        Cmin[i] = INFINIT;
    }

    int x, y, c;
    optim = false;
    Cmin[1] = 0;

    while(inc <= sf)
    {
        x = Q[inc++];

        for(i = 1; i <= count[x]; i++)
        {
            y = C[x][i].next_node;
            c = C[x][i].cost;

            if(Cmin[x] + c < Cmin[y])
            {
                Cmin[y] = Cmin[x]+c;
                Q[++sf] = y;
                nrpus[y]++;
                if(nrpus[y] >= n)
                {
                    optim = true;
                    sf = -1;
                    break;
                }
            }
        }
    }
}

void afisare()
{
    if(optim) fout << "Ciclu negativ!";
    else
    for(int i = 2; i <= n; i++)
    {
        fout << Cmin[i] << ' ';
    }

    fout.close();
}