Cod sursa(job #528185)

Utilizator DraStiKDragos Oprica DraStiK Data 2 februarie 2011 12:39:07
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

#define INF 0x3f3f3f3f
#define pb push_back
#define mp make_pair
#define DIM 50005
#define sc second
#define fs first

vector <pair <int,int> > g[DIM];
int dst[DIM],use[DIM];
bool viz[DIM];
queue <int> q;
int n,m,ok;

void read ()
{
    int i,x,y,z;

    scanf ("%d%d",&n,&m);
    for (i=1; i<=m; ++i)
    {
        scanf ("%d%d%d",&x,&y,&z);
        g[x].pb (mp (y,z));
    }
}

void solve ()
{
    vector <pair <int,int> > :: iterator it;
    int nod;

    memset (dst,INF,sizeof (dst));
    dst[1]=0; use[1]=1;

    for (q.push (1); !q.empty (); q.pop ())
    {
        viz[nod=q.front ()]=0;
        for (it=g[nod].begin (); it!=g[nod].end (); ++it)
            if (dst[nod]+it->sc<dst[it->fs])
            {
                dst[it->fs]=dst[nod]+it->sc;
                if (!viz[it->fs])
                {
                    viz[it->fs]=1;
                    q.push (it->fs);
                }
                if (++use[it->fs]==n)
                {
                    ok=1;
                    return ;
                }
            }
    }
}

void print ()
{
    int i;

    if (ok)
        printf ("Ciclu negativ!");
    else
        for (i=2; i<=n; ++i)
            printf ("%d ",dst[i]);
}

int main ()
{
    freopen ("bellmanford.in","r",stdin);
    freopen ("bellmanford.out","w",stdout);

    read ();
    solve ();
    print ();

    return 0;
}