Cod sursa(job #399699)

Utilizator DraStiKDragos Oprica DraStiK Data 20 februarie 2010 22:19:33
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.18 kb
#include <algorithm>
#include <vector>
using namespace std;

#define INF 0x3f3f3f3f
#define pb push_back
#define mp make_pair
#define DIM 50005
#define sc second
#define fs first

vector <pair <int,int> > g[DIM];
int dst[DIM],h[DIM],poz[DIM];
int n,m,l;

void read ()
{
    int i,x,y,z;

    scanf ("%d%d",&n,&m);
    for (i=1; i<=m; ++i)
    {
        scanf ("%d%d%d",&x,&y,&z);
        g[x].pb (mp (y,z));
    }
}

void upheap (int nod)
{
    int tata;

    for ( ; nod>1; )
    {
        tata=nod>>1;
        if (dst[h[tata]]>dst[h[nod]])
        {
            poz[h[tata]]=nod;
            poz[h[nod]]=tata;
            swap (h[tata],h[nod]);
            nod=tata;
        }
        else
            return ;
    }
}

void downheap (int nod)
{
    int fiu;

    for ( ; nod<=l; )
    {
        if ((nod<<1)<=l)
        {
            if ((nod<<1)+1<=l)
                if (dst[h[fiu]]<dst[h[fiu+1]])
                    ++fiu;
        }
        else
            return ;
        if (dst[h[fiu]]<dst[h[nod]])
        {
            poz[h[fiu]]=nod;
            poz[h[nod]]=fiu;
            swap (h[nod],h[fiu]);
            nod=fiu;
        }
        else
            return ;
    }
}

void solve ()
{
    int nod,i;

    memset (dst,INF,sizeof (dst));
    for (dst[1]=0, poz[h[l=1]=1]=1; l; )
    {
        nod=h[1];
        h[1]=h[l--];
        poz[h[1]]=1;
        downheap (1);
        for (i=0; i<(int)g[nod].size (); ++i)
            if (dst[nod]+g[nod][i].sc<dst[g[nod][i].fs])
            {
                dst[g[nod][i].fs]=dst[nod]+g[nod][i].sc;
                if (poz[g[nod][i].fs])
                    upheap (poz[g[nod][i].fs]);
                else
                {
                    poz[h[++l]=g[nod][i].fs]=l;
                    upheap (l);
                }
            }
    }
}

void print ()
{
    int i;

    for (i=2; i<=n; ++i)
        if (dst[i]==INF)
            printf ("0 ");
        else
            printf ("%d ",dst[i]);
}

int main ()
{
    freopen ("dijkstra.in","r",stdin);
    freopen ("dijkstra.out","w",stdout);

    read ();
    solve ();
    print ();

    return 0;
}