Cod sursa(job #736502)

Utilizator BitOneSAlexandru BitOne Data 18 aprilie 2012 20:26:31
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <vector>
#include <fstream>
#include <cstdlib>
#include <iterator>
#include <algorithm>


using namespace std;

const int oo=1<<29;
const int N_MAX=50011;
typedef pair<int, int> pr;

vector<pr> G[N_MAX];
vector<pr>::const_iterator it, iend;

int lHeap;
int d[N_MAX], H[N_MAX], P[N_MAX];

inline void _swap(int &x, int &y) {int aux=x; x=y; y=aux;}
void DownHeap(int k)
{
    for(int son=k<<1; son <= lHeap; k=son, son<<=1)
    {
        if(son < lHeap && d[H[son]] > d[H[son+1]])
            ++son;
        if(d[H[k]] <= d[H[son]])
            return;
        _swap(H[k], H[son]);
        P[H[k]]=k;
        P[H[son]]=son;
    }
}
void UpHeap(int k)
{
    for(int key=d[H[k]], f=k>>1; k > 1 && key < d[H[f]]; k=f, f>>=1)
    {
        _swap(H[k], H[f]);
        P[H[k]]=k;
        P[H[f]]=f;
    }
}
inline void push(int x)
{
    H[++lHeap]=x;
    P[x]=lHeap;
    UpHeap(lHeap);
}
inline int pop()
{
    int r=H[1];

    P[H[1]]=-1;
    H[1]=H[lHeap];
    P[H[1]]=1;
    --lHeap;
    DownHeap(1);

    return r;
}
int main()
{
    int N, M, x, y, c;
    ifstream in("dijkstra.in");
    ofstream out("dijkstra.out");

    for(in>>N>>M; M; --M)
    {
        in>>x>>y>>c;
        G[x].push_back(pr(y, c));
    }
    fill(d+1, d+N+1, oo);
    for(d[1]=0, push(1); lHeap; )
    {
        x=pop();
        for(it=G[x].begin(), iend=G[x].end(); it < iend; ++it)
            if(d[it->first] > d[x]+it->second)
            {
                if(oo == d[it->first])
                {
                    d[it->first]=d[x]+it->second;
                    push(it->first);
                }
                else UpHeap(P[it->first]);
            }
    }
    replace(d+1, d+N+1, oo, 0);
    copy(d+2, d+N+1, ostream_iterator<int>(out, " "));

    return EXIT_SUCCESS;
}