Cod sursa(job #1631992)

Utilizator TibixbAndrei Tiberiu Tibixb Data 5 martie 2016 20:46:43
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
#include<fstream>
#include<vector>
#include<cstring>
#define inf 0x7f7f7f7f
using namespace std;
vector<pair<int, int> > L[50005];
int n, m, i, x, y, z, D[50005], h[50005], p[50005], s, p1, nrh, nod, vecin, cost;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
int main()
{
    in>>n>>m;
    for(i=1; i<=m; i++)
    {
        in>>x>>y>>z;
        L[x].push_back(make_pair(y, z));
    }
    memset(D, 127, sizeof(D));
    D[1]=0;
    h[++nrh]=1;
    p[1]=1;
    while(nrh!=0)
    {
        nod=h[1];
        h[1]=h[nrh];
        nrh--;
        p[h[1]]=1;
        s=1;
        p1=2;
        while(s<=nrh)
        {
            if(s+1<=nrh && D[h[s+1]]<D[h[s]])
                s++;
            if(D[h[s]]<D[h[p1]])
            {
                swap(h[s], h[p1]);
                p[h[s]]=s;
                p[h[p1]]=p1;
                p1=s;
                s*=2;
            }else
            {
                break;
            }
        }
        for(i=0; i<L[nod].size(); i++)
        {
            vecin=L[nod][i].first;
            cost=L[nod][i].second;
            if(D[vecin]>D[nod]+cost)
            {
                D[vecin]=D[nod]+cost;
                if(p[vecin]!=0)
                {
                    s=p[vecin];
                    p1=s/2;
                }else
                {
                    h[++nrh]=vecin;
                    p[vecin]=nrh;
                    s=nrh;
                    p1=s/2;
                }
                while(p1!=0 && D[h[s]]<D[h[p1]])
                {
                    swap(h[s], h[p1]);
                    p[h[s]]=s;
                    p[h[p1]]=p1;
                    s=p1;
                    p1/=2;
                }
            }
        }
    }
    for(i=2; i<=n; i++)
        D[i]!=inf?out<<D[i]<<" ":out<<"0 ";
    return 0;
}