Cod sursa(job #1738387)

Utilizator catalin9898Bajenaru Catalin catalin9898 Data 6 august 2016 16:42:41
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <cstdio>
#include <vector>
using namespace std;
int nn,cost[50001],h[50001],poz[50001] ;
struct vert
{
    int nod,cost;
} ad;

vector<vert>v[50001];
vector<vert>::const_iterator in,fi;



void sw(int a, int b)
{
    int aux;
    aux=h[a];
    h[a]=h[b];
    h[b]=aux;
    poz[h[a]]=a;
    poz[h[b]]=b;
}

int sift()
{
    sw(1,nn);
    nn--;
    int son=2,tata=1;
    while(son<=nn)
    {
        if(son<nn&&cost[h[son]]>cost[h[son+1]])son++;
        if(cost[h[tata]]>cost[h[son]])
        {
            sw(tata,son);
            tata=son;
            son*=2;
        }
        else break;
    }
    return h[nn+1];
}
void percolate(int fiu)
{
    int tata=fiu/2;
    while(tata>=1)
    {
        if(cost [h[tata]]>cost[h[fiu]])
        {
            sw(tata,fiu);
            fiu=tata;
            tata/=2;
        }
        else break;
    }
}



int main()
{
    freopen("in.in","r",stdin);
    freopen("out.out","w",stdout);
    int i,j,n,m,a,b,c;
    scanf("%d%d",&n,&m);
    nn=n;
    for(i=1; i<=m; i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        ad.cost=c;
        ad.nod=b;
        v[a].push_back(ad);
    }
    for(i=1; i<=n; i++)
    {
        cost[i]=12345678;
        poz[i]=h[i]=i;
    }
    cost[1]=0;
    int ok=1;
    while(ok)
    {

        ok=0;
        a=sift();
        //  in=v[a].begin();fi=v[a].end();
        for(i=0; i<v[a].size(); i++)
        {
            if(v[a][i].cost+cost[a]<cost[v[a][i].nod])
            {
                cost[v[a][i].nod]= v[a][i].cost+cost[a];
                percolate(poz[v[a][i].nod]);
                ok=1;
            }
        }

    }
    for(i=2; i<=n; i++)
    {
        if(cost[i]==12345678)printf("0 ");
        else printf("%d ",cost[i]);
    }

    return 0;
}