Cod sursa(job #1580120)

Utilizator sicsicFMI-Coteanu Vlad sicsic Data 25 ianuarie 2016 16:37:00
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include<fstream>
#include<queue>
#define INF 99999999
#define Nmax 50003
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int N,D[Nmax],M;
bool U[Nmax];
struct cmp
{
    bool operator()(int &a,int &b)
    {
        return D[a]>D[b];
    }
};
priority_queue<int,vector<int>,cmp>H;
struct lista{int nod,cost; lista *leg;} *G[Nmax];
void adaug(int i,int j,int c)
{
    lista *p;
    p=new lista;
    p->nod=j;
    p->cost=c;
    p->leg=G[i];
    G[i]=p;
}
void citire()
{
    f>>N>>M;
    int i,j,c;
    while(M--)
    {
        f>>i>>j>>c;
        adaug(i,j,c);
        adaug(j,i,c);
    }
}
void Dyj()
{
    for(int i=1;i<=N;++i) D[i]=INF;
    D[1]=0; U[1]=1;
    for(H.push(1);!H.empty();H.pop())
    {
        int nod=H.top(); U[nod]=0;
        for(lista *p=G[nod];p;p=p->leg)
            if(D[p->nod]>D[nod]+p->cost)
            {
                D[p->nod]=D[nod]+p->cost;
                if(!U[p->nod])
                {
                    U[p->nod]=1;
                    H.push(p->nod);
                }
            }
    }
}
int main()
{
    citire();
    Dyj();
    for(int i=2;i<=N;++i)
        if(D[i]==INF) g<<"0 ";
        else g<<D[i]<<" ";
    g<<'\n';
    return 0;
}