Cod sursa(job #380971)

Utilizator cristikIvan Cristian cristik Data 8 ianuarie 2010 14:09:47
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <stdio.h>
#include <vector>
#include <set>
#define max 200010
const int inf=0x3f3f3f3f;
using namespace std;
struct lista
{
    int nod,cost;
    lista *next;
};
lista *g[max],*p;
int n,m,i,j,cost1,d[max],t[max],k,w;
char inq[max];
struct cmp{
    bool operator () (int i,int j)
    { return d[i] < d[j]; }
};
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;
}
multiset <int,cmp> q;
multiset<int>::iterator it;
int main()
{
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(; m>0; m--)
    {
        scanf("%d%d%d",&i,&j,&cost1);
        push(i,j,cost1);
    }
    memset(d,inf,sizeof(d));
    d[1]=0; inq[1]=1; q.insert(1);
    while(!q.empty())
    {
        k=*q.begin();
        q.erase(q.begin());
        inq[k]=0;
        for(p=g[k]; p!=NULL; p=p->next)
         if(d[p->nod]>d[k]+p->cost)
         {
             w=p->nod;
             if(inq[w]) q.erase(w);
             d[w]=d[k]+p->cost;
             q.insert(w);
         }
    }
    for(i=2; i<=n; i++)
     if(d[i]!=inf) printf("%d ",d[i]);
     else printf("0 ");
    return 0;
}