Mai intai trebuie sa te autentifici.

Cod sursa(job #1906631)

Utilizator raduzxstefanescu radu raduzx Data 6 martie 2017 15:29:14
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.32 kb
#include <fstream>

using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
#define inf 2000000000
struct nod
{
    int where,cost;
    nod *urm;
};
typedef nod *pnod;
pnod v[50003],p;
void ad(int x,int y,int cost)
{
    p=new nod;
    p->where=y;
    p->cost=cost;
    p->urm=v[x]->urm;
    v[x]->urm=p;
}
int n,m;
int dist[50003],poz[50003],h[50003];
void upheap(int what)
{
    int tata;
    while ( what > 1 )
    {
        tata = what >> 1;

        if ( dist[ poz[tata] ] > dist[ poz[what] ] )
        {
            swap(h[poz[tata]],h[poz[what]]);
            swap(poz[tata],poz[what]);

            what = tata;
        }
        else
            what = 1;
    }
}
int k;
void downheap(int fi)
{
    int now;
    do
    {
        now=0;
        if(fi*2<=k)
        {
            now=fi*2;
            if(now+1<=k and dist[poz[now+1]]<dist[poz[now]])
                now+=1;
            if(dist[poz[fi]]>dist[poz[now]])
            {
                swap(h[poz[fi]],h[poz[now]]);
                swap(poz[now],poz[fi]);
                fi=now;
            }
            else
                now=0;
        }
    }while(now);
}
int main()
{
    int i,x,y,c;
    f>>n>>m;
    for(i=1;i<=n;i++)
    {
        v[i]=new nod;
        v[i]->urm=0;
        dist[i]=inf;
        h[i]=-1;
    }
    for(i=1;i<=m;i++)
    {
        f>>x>>y>>c;
        ad(x,y,c);
    }
    p=v[1]->urm;
    dist[1]=0;
    h[1]=1;
    k=1;
    int minim;
    poz[1]=1;
    while(k)
    {
        minim=poz[1];
        swap(poz[1],poz[k]);
        h[poz[1]]=1;
        k--;
        downheap(1);

        p=v[minim]->urm;
        while(p)
        {
            if(dist[p->where]>dist[minim]+p->cost)
            {
                dist[p->where]=dist[minim]+p->cost;
                if(h[p->where]==-1)
                {
                    k+=1;
                    poz[k]=p->where;
                    h[p->where]=k;
                    upheap(k);
                }
                else
                {
                    upheap(h[p->where]);
                }
            }
            p=p->urm;
        }
    }
    for(i=2;i<=n;i++)
        if(dist[i]==inf)
            g<<"0 ";
        else
            g<<dist[i]<<" ";
    g<<'\n';
    return 0;
}