Cod sursa(job #520805)

Utilizator mytzuskyMihai Morcov mytzusky Data 10 ianuarie 2011 13:55:37
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <fstream>
#include <queue>

#define nmax 50001
#define oo 0x3f3f3f3f


using namespace std;

queue <int> Q;

int n,m,dist[nmax],incoada[nmax];
bool viz[nmax];
bool ok = true;

struct nod{
    int inf,cost;
    nod *urm;
} *g[nmax];


void add(int x,int y,int z)
{
    nod *aux = new nod;
    aux->inf  = y;
    aux->cost = z;
    aux->urm = g[x];
    g[x] = aux;
}

int main()
{
    ifstream f("bellmanford.in");
    ofstream gg("bellmanford.out");

    f>>n>>m;
    int x,y,z;
    for(int i=1;i<=m;++i)
    {
        f>>x>>y>>z;
        add(x,y,z);
    }

    Q.push(1);
    viz[1] = true;
    memset(dist,oo,sizeof(dist));
    dist[1] = 0;

    while( !Q.empty())
    {
        int nd = Q.front();
        Q.pop();
        viz[nd]=false;

        for(nod *p=g[nd];p;p=p->urm)
        {
            if(dist[nd] + p->cost < dist[p->inf])
            {
                dist[p->inf] = p->cost + dist[nd];
                if(viz[p->inf] == false)
                {
                    if(incoada[p->inf] > n)
                        ok = false;

                    else{
                    Q.push(p->inf);
                    viz[p->inf]=true;
                    incoada[p->inf]++;
                    }
                }
            }
        }
    }



    if( ok==true )
        for(int i=2;i<=n;++i)
           if(dist[i] == oo)
                gg<<0<<" ";
           else
                gg<<dist[i]<<" ";
    else
        gg<<"Ciclu negativ!\n";
    f.close();
    gg.close();

    return 0;
}