Cod sursa(job #1017094)

Utilizator andreiiiiPopa Andrei andreiiii Data 27 octombrie 2013 10:53:02
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.11 kb
#include <algorithm>
#include <cstdio>
#include <cstring>
#define N 50002
#define INF 0x3f3f3f3f
using namespace std;

struct graf
{
    int n, cost;
    graf *next;
};

graf *g[N];
int d[N], poz[N], h[N];
int n;

inline void Read()
{
    freopen("dijkstra.in", "r", stdin);
    int m, x, y, cost;
    scanf("%d%d", &n, &m);
    while(m--)
    {
        scanf("%d%d%d", &x, &y, &cost);
        graf *p=new graf;
        p->n=y;
        p->cost=cost;
        p->next=g[x];
        g[x]=p;
    }
}

inline void Write()
{
    freopen("dijkstra.out", "w", stdout);
    for(int i=2;i<=n;i++)
    {
        printf("%d ", d[i]);
    }
}

void upheap(int x)
{
    int f;
    while(x>1)
    {
        f=x/2;
        if(d[h[f]]>d[h[x]])
        {
            poz[h[f]]=x;
            poz[h[x]]=f;
            swap(h[f], h[x]);
            x=f;
        }
        else return;
    }
}

void downheap(int x)
{
    int s;
    while(x<=h[0])
    {
        s=x;
        if(2*x<=h[0])
        {
            s=2*x;
            if(s+1<=h[0]&&d[h[s+1]]<d[h[s]]) s++;
        }
        else return;
        if(d[h[x]]>d[h[s]])
        {
            poz[h[x]]=s;
            poz[h[s]]=x;
            swap(h[x], h[s]);
            x=s;
        }
        else return;
    }
}

inline void dijkstra()
{
    int i, x;
    graf *p;
    memset(d, INF, sizeof(d));
    memset(poz, 0xff, sizeof(poz));
    poz[1]=1;
    d[1]=0;
    h[++h[0]]=1;
    while(h[0])
    {
        x=h[1];
        swap(h[1], h[h[0]]);
        poz[h[1]]=1;
        h[0]--;
        downheap(1);
        for(p=g[x];p;p=p->next)
        {
            if(d[p->n]>d[x]+p->cost)
            {
                d[p->n]=d[x]+p->cost;
                if(poz[p->n]!=-1)
                {
                    upheap(poz[p->n]);
                }
                else
                {
                    h[++h[0]]=p->n;
                    poz[p->n]=h[0];
                    upheap(h[0]);
                }
            }
        }
    }
}

int main()
{
    Read();
    dijkstra();
    Write();
}