Cod sursa(job #1515178)

Utilizator NightSilentIridon Stefan NightSilent Data 1 noiembrie 2015 11:26:19
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.28 kb
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
struct nod
{
    int inf,cost;
    nod *urm;
};
nod *l[50001];
int n,m,s,d[50001,t[50001],h[50001,poz[50001],nh,u[50001];
void adaugnod(nod *&p,int x,int val)
    {
        nod *c;
        c=new nod;
        c->inf=x;
        c->cost=val;
        c->urm=p;
        p=c;
    }
void citire()
    {
        int i;
        int x,y,val;
        f>>n>>m;
        for (i=1;i<=m;i++)
            {
                f>>x>>y>>val;
                adaugnod(l[x],y,val);
                adaugnod(l[y],x,val);
            }
        f.close();
    }
void swap (int i,int j)
{
    int t;
    t=h[i];
    h[i]=h[j];
    h[j]=t;
    poz[h[i]]=i;
    poz[h[j]]=j;
}
void heap_dw(int r,int k)
{
    int st,dr,i;
    if (2*r+1<=k)
    {
        st=h[2*r+1];
        if (2*r+2<=k)
            dr=h[2*r+2];
        else
            dr=st-1;
        if (st>dr)
            i=2*r+1;
        else
            i=2*r+2;
        if (d[h[r]]>d[h[i]])
            {
                swap(r,i);
                heap_dw(i,k);
            }
    }
}
void heap_up(int k)
{
    int t;
    if (k<=0)
        return;
    t=(k-1)/2;
    if (d[h[k]]<d[h[t]])
        {
            swap(k,t);
            heap_up(t);
        }

}
void build_h(int k)
{
    int i;
    for (i=1;i<k;i++)
        heap_up(i);
}
int scoate_heap()
{
    swap(0,nh-1);
    poz[h[nh-1]]=0;
    nh--;
    heap_dw(0,nh-1);
    return h[nh];
}
void dijkstra (int sursa)
{
    int i,inf;
    memset(d,0x3f,sizeof(d));
    nod *p;
    for (i=0;i<n;i++)
    {
        h[i]=i+1;
        poz[i+1]=i;

    }
    d[sursa]=0;
    build_h(n);
    nh=n;
    while (nh>0)
    {
        inf=scoate_heap();
        for (p=l[inf];p;p=p->urm)
            if (d[p->inf]>d[inf]+p->cost)
                {
                    d[p->inf]=d[inf]+p->cost;
                    t[p->inf]=inf;
                    heap_up(poz[p->inf]);
                }
    }
}
int main()
{
    int i;
    citire();
    dijkstra(1);
    for (i=2;i<=n;i++)
        if (d[i]!=0x3f)
        {

            g<<d[i]<<" ";
        }
        else
        g<<0<<" ";
    return 0;
}