Cod sursa(job #881981)

Utilizator VladMSBonta vlad valentin VladMS Data 18 februarie 2013 20:00:57
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>
#define pinf 1<<30
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
struct nod
{
    int urm,cost,ant;
    nod *next;
};
nod *p,*l[50001];
int x,y,i,j,n,nods,viz[50001],d[50001],t[50001],minn,poz,c,m,ok,st,w,z;
int main()
{
    fin>>n>>m;
    for(i=1;i<=m;++i)
    {
        fin>>x>>y>>c;
        p=new nod;
        p->next=l[x];
        p->urm=y;
        p->ant=x;
        p->cost=c;
        l[x]=p;
        if(x==1)
        {
            d[y]=c;
            t[y]=x;
            if(d[y]<minn||minn==0)
                {
                    minn=d[y];
                    poz=y;
                }
        }
    }
    viz[1]=1;
    ok=1;
    st=poz;
    for(i=1;i<=n;++i)
        if(d[i]==0&&i!=1)
            d[i]=pinf;

    while(ok==1)
    {
        viz[st]=1;
        p=new nod;
        p=l[st];
        while(p)
        {
            z=p->urm;
            w=p->ant;
            c=p->cost;
            if(viz[z]==0)
                if(d[w]+c<d[z])
                {
                    d[z]=d[w]+c;
                    t[z]=w;
                }


            p=p->next;
        }
        minn=0;
        poz=0;
        ok=0;
        for(i=2;i<=n;++i)
            if(viz[i]==0&&(d[i]<minn||minn==0))
            {
              minn=d[i];
              st=i;
              ok=1;
            }
    }
    for(i=2;i<=n;++i)
        if(d[i]==pinf)
            fout<<0<<" ";
        else
            fout<<d[i]<<" ";

    return 0;
}