Cod sursa(job #406333)

Utilizator DraStiKDragos Oprica DraStiK Data 1 martie 2010 14:09:40
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.23 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));
    }
}

inline void upheap (int nod)
{
    int tata;

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

inline void downheap (int nod)
{
    int fiu;

    for ( ; nod<=l; )
    {
        if ((nod<<1)<=l)
        {
            fiu=nod<<1;
            if (fiu+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 ()
{
    vector <pair <int,int> > :: iterator it;
    int nod;

    memset (dst,INF,sizeof (dst));

    poz[h[l=1]=1]=1;
    for (dst[1]=0; l; )
    {
        nod=h[1];
        h[1]=h[l--];
        poz[h[1]]=1;
        downheap (1);
        for (it=g[nod].begin (); it!=g[nod].end (); ++it)
            if (dst[nod]+it->sc<dst[it->fs])
            {
                dst[it->fs]=dst[nod]+it->sc;
                if (poz[it->fs])
                    upheap (poz[it->fs]);
                else
                {
                    poz[h[++l]=it->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;
}