Cod sursa(job #594281)

Utilizator Magnuscont cu nume gresit sau fals Magnus Data 6 iunie 2011 21:56:20
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.25 kb
#include <fstream>
#include <vector>

using namespace std;

const int INF=2000000005;
vector <int> G[50005];
vector <int> C[50005];
int D[50005], H[50005], P[50005], NH;
unsigned int N;

void Read ()
{
    ifstream fin ("dijkstra.in");
    int M, X, Y, Z;
    fin >> N >> M;
    for (; M>0; --M)
    {
        fin >> X >> Y >> Z;
        G[X].push_back (Y);
        C[X].push_back (Z);
    }
    fin.close ();
}

void Type ()
{
    ofstream fout ("dijkstra.out");
    unsigned int i;
    for (i=2; i<=N; ++i)
    {
        if (D[i]==INF)
        {
            D[i]=0;
        }
        fout << D[i] << " ";
    }
    fout << "\n";
    fout.close ();
}

inline void Swap (int X, int Y)
{
    int Aux;
    Aux=P[H[X]];
    P[H[X]]=P[H[Y]];
    P[H[Y]]=Aux;
    Aux=H[X];
    H[X]=H[Y];
    H[Y]=Aux;
}

void Sift (int X)
{
    int S=X<<1;
    while (S<=NH)
    {
        if ((X<<1)<NH&&D[H[S]]>D[H[(X<<1)+1]])
            ++S;
        if (D[H[S]]<D[H[X]])
        {
            Swap (X, S);
            X=S;
            S=X<<1;
        }
        else
        {
            return;
        }
    }
}

void Percolate (int X)
{
    int F=X>>1;
    while (F)
    {
        if (D[H[F]]>D[H[X]])
        {
            Swap (X, F);
            X=F;
            F=X>>1;
        }
        else
            return;
    }
}

inline void Insert (int X)
{
    H[++NH]=X;
    P[H[NH]]=NH;
    Percolate (NH);
}

inline void Delete (int X)
{
    H[X]=H[NH--];
    P[H[X]]=1;
    Sift (X);
}

void Dijkstra (int Start)
{
    unsigned int i;
    int NC;
    for (i=1; i<=N; ++i)
    {
        P[i]=-1;
        D[i]=INF;
    }
    D[Start]=0;
    P[Start]=1;
    H[++NH]=Start;
    while (NH>0)
    {
        NC=H[1];
        Delete (1);
        for (i=0; i<G[NC].size (); ++i)
        {

            if (P[G[NC][i]]==-1)
            {
                D[G[NC][i]]=D[NC]+C[NC][i];
                Insert (G[NC][i]);
            }
            if (D[G[NC][i]]>D[NC]+C[NC][i])
            {
                D[G[NC][i]]=D[NC]+C[NC][i];
                Percolate (P[G[NC][i]]);
            }
        }
    }
}

int main()
{
    Read ();
    Dijkstra (1);
    Type ();
    return 0;
}