Cod sursa(job #1274921)

Utilizator andi12Draghici Andrei andi12 Data 24 noiembrie 2014 16:16:14
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <cstdio>

using namespace std;
const int N=50000;
const int M=250000;
int lst[N+1],vf[M+1],urm[M+1],h[N+1],sum[N+1],cost[M+1],jmen[N+1];
bool viz[N+1];
int p,nrh;
void schimba(int x,int y)
{
    int aux;
    aux=h[x];
    h[x]=h[y];
    h[y]=aux;
    jmen[h[x]]=x;
    jmen[h[y]]=y;
}
void ad(int x,int y,int c)
{
    p++;
    vf[p]=y;
    urm[p]=lst[x];
    lst[x]=p;
    cost[p]=c;
}
void urca(int poz)
{
    if(poz/2>=1 && sum[h[poz/2]]>sum[h[poz]])
    {
        schimba(poz,poz/2);
        urca(poz/2);
    }
}
void coboara(int poz)
{
    int bun=poz,fs=2*poz,fd=2*poz+1;
    if(fs<=nrh && sum[h[nrh]]>sum[h[bun]]) bun=fs;
    if(fd<=nrh && sum[h[nrh]]>sum[h[bun]]) bun=fd;
    if(bun!=poz)
    {
        schimba(poz,bun);
        coboara(bun);
    }
}
void adh(int x)
{
    nrh++;
    h[nrh]=x;
    jmen[x]=nrh;
    urca(nrh);
}
void del(int x)
{
    nrh--;
    h[x]=h[nrh+1];
    coboara(x);
}
void bfs(int x)
{
    int poz,val;
    adh(x);
    while(nrh>0)
    {
        poz=lst[h[1]];
        val=sum[h[1]];
        del(1);
        while(poz!=0)
        {
            if(sum[vf[poz]]==0)
            {
                sum[vf[poz]]=val+cost[poz];
                adh(vf[poz]);
            }
            poz=urm[poz];
        }
    }
}
int main()
{
    FILE *in,*out;
    in=fopen("dijkstra.in","r");
    out=fopen("dijkstra.out","w");
    int n,m,x,y,i,j,c;
    fscanf(in,"%d%d",&n,&m);
    for(i=1;i<=m;i++)
    {
        fscanf(in,"%d%d%d",&x,&y,&c);
        ad(x,y,c);
    }
    bfs(1);
    for(i=2;i<=n;i++)
        fprintf(out,"%d ",sum[i]);
    return 0;
}