Cod sursa(job #604370)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 22 iulie 2011 00:05:02
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <iostream>
#include <vector>
#include <queue>

#define NMax 50005
#define Inf 2000000000
#define v first
#define c second

using namespace std;

vector < pair <int, int> > G[NMax];
int N, NQ[NMax], D[NMax];
queue <int> Q;
bool InQ[NMax], NegativeCycle;

void Read ()
{
    freopen ("bellmanford.in", "r", stdin);
    int M;
    scanf ("%d %d", &N, &M);
    for (; M>0; --M)
    {
        int X, Y, Z;
        scanf ("%d %d %d", &X, &Y, &Z);
        G[X].push_back (make_pair (Y, Z));
    }
}

void Print ()
{
    freopen ("bellmanford.out", "w", stdout);
    if (NegativeCycle)
    {
        printf ("Ciclu negativ!\n");
    }
    else
    {
        for (int i=2; i<=N; ++i)
        {
            printf ("%d ", D[i]);
        }
        printf ("\n");
    }
}

void Initialize (int Start)
{
    for (int i=1; i<=N; ++i)
    {
        D[i]=Inf;
    }
    D[Start]=0;
    Q.push (Start);
    InQ[Start]=true;
    NQ[Start]=1;
}

void BellmanFord (int Start)
{
    Initialize (Start);
    while (!Q.empty ())
    {
        int X=Q.front ();
        Q.pop ();
        InQ[X]=false;
        for (unsigned i=0; i<G[X].size (); ++i)
        {
            int V=G[X][i].v;
            int C=G[X][i].c;
            if (D[X]+C<D[V])
            {
                D[V]=D[X]+C;
                if (!InQ[V])
                {
                    Q.push (V);
                    InQ[V]=true;
                }
                ++NQ[V];
                if (NQ[V]>=N)
                {
                    NegativeCycle=true;
                    return;
                }
            }
        }
    }
}

int main()
{
    Read ();
    BellmanFord (1);
    Print ();
    return 0;
}