Cod sursa(job #1846484)

Utilizator rnqftwcalina florin daniel rnqftw Data 12 ianuarie 2017 22:37:23
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.46 kb
#include <fstream>
#include <cstdio>
const int MAX = 50001;
const int inf = 1 << 30;



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

int n, m;
graf *a[MAX];
int d[MAX], h[MAX], poz[MAX], k;

void adaugare(int prim, int ultim, int cost)
{
    graf *q = new graf;
    q->nod = ultim;
    q->cost = cost;
    q->next = a[prim];
    a[prim] = q;
}

void citeste()
{
    ifstream f1("dijkstra.in");
    f1>>&n>>&m;

    int x, y, z;
    for ( int i = 1; i <= m; ++i )
    {
        f1>>&x>>&y>>&z;
        add(x, y, z);
    }
    f1.close();
}

void schimba(int x, int y)
{
    int t = h[x];
    h[x] = h[y];
    h[y] = t;
}

void urca(int what)
{
    int tata;
    while ( what > 1 )
    {
        tata = what >> 1;

        if ( d[ h[tata] ] > d[ h[what] ] )
        {
            poz[ h[what] ] = tata;
            poz[ h[tata] ] = what;

            schimba(tata, what);

            what = tata;
        }
        else
            what = 1;
    }
}

void coboara(int what)
{
    int f;
    while ( what <= k )
    {
        f = what;
        if ( (what<<1) <= k )
        {
            f = what << 1;
            if ( f + 1 <= k )
                if ( d[ h[f + 1] ] < d[ h[f] ] )
                    ++f;
        }
        else
            return;

        if ( d[ h[what] ] > d[ h[f] ] )
        {
            poz[ h[what] ] = f;
            poz[ h[f] ] = what;

            schimba(what, f);

            what = f;
        }
        else
            return;
    }
}

void dijkstra_heap()
{
    for ( int i = 2; i <= n; ++i )
        d[i] = inf, poz[i] = -1;
    poz[1] = 1;

    h[++k] = 1;

    while ( k )
    {
        int min = h[1];
        schimba(1, k);
        poz[ h[1] ] = 1;
        --k;

        coboara(1);

        graf *q = a[min];

        while ( q )
        {
            if ( d[q->nod] > d[min] + q->cost )
            {
                d[q->nod] = d[min] + q->cost;

                if ( poz[q->nod] != -1 )
                    urca( poz[q->nod] );
                else
                {
                    h[++k] = q->nod;
                    poz[ h[k] ] = k;
                    urca( k );
                }
            }
            q = q->next;
        }
    }
}

int main()
{
       ofstream f2("dijkstra.out")
    citeste();
    dijkstra_heap();

    for ( int i = 2; i <= n; ++i )
        f2<<d[i]<<" ";
 f2.close();
    return 0;
}