Cod sursa(job #412513)

Utilizator cristikIvan Cristian cristik Data 5 martie 2010 19:40:25
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <stdio.h>
#include <string.h>
#define maxn 50010
const int inf=0x3f3f3f3f;
struct lista
{
    int nod,cost;
    lista *next;
};
lista *g[maxn],*p;
int q[5*maxn],d[maxn],i,j,n,m,k,cost,ultim,prim,u,w;
char inq[5*maxn];
void push(int i,int j,int c)
{
    lista *p=new lista;
    p->cost=c;
    p->nod=j;
    p->next=g[i];
    g[i]=p;
}
int main()
{
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(; m--; )
    {
        scanf("%d%d%d",&i,&j,&cost);
        push(i,j,cost);
    }
    memset(d,inf,sizeof(d));
    d[1]=0; q[0]=1;
    while(prim<=ultim)
    {
        u=q[prim++];
        inq[u]=0;
        for(p=g[u]; p!=NULL; p=p->next)
        {
            w=p->nod;
            if(d[w]>d[u]+p->cost)
            {
                if(!inq[w])
                {
                    inq[w]=1;
                    q[++ultim]=w;
                }
                d[w]=d[u]+p->cost;
            }
        }
    }
    for(i=2; i<=n; i++)
     if(d[i]!=inf) printf("%d ",d[i]);
     else printf("0 ");
    return 0;
}