Cod sursa(job #1488819)

Utilizator DeltaMTP Dragos DeltaM Data 19 septembrie 2015 21:53:13
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include<cstdio>
#include<vector>
#define dmax 2000000000
using namespace std;
vector< pair<int,int> >L[50100];
int n,m,i,j,a,b,c,poz,dh,ih,d[50100],h[50100],x[50100];
FILE *f,*g;
void chg(int &a,int &b){
    int aux=a;
    a=b;
    b=aux;
}
void del(){
    h[1]=h[dh--];
    int p=1;
    int c=2;
    while(c<=dh){
        if( d[ h[c] ] > d[ h[c+1] ] )
            c++;
        if(d[ h[c] ] < d[ h[p] ]){
            chg(h[c],h[p]);
            x[ h[c] ]=c;
            x[ h[p] ]=p;
            p=c;
            c*=2;
        }
        else
            break;
    }
}
void upd(int poz){
    int c=poz;
    int p=c/2;
    while(p>=1){
        if( d[ h[c] ] < d[ h[c+1] ] )
            c++;
        if( d[ h[c] ] > d[ h[p] ] ){
            chg(h[c],h[p]);
            x[ h[c] ]=c;
            x[ h[p] ]=p;
            c=p;
            p/=2;
        }
        else
            break;
    }
}
int main(){
    f=fopen("dijkstra.in","r");
    g=fopen("dijkstra.out","w");
    fscanf(f,"%d%d",&n,&m);
    for(i=1;i<=m;i++){
        fscanf(f,"%d%d%d",&a,&b,&c);
        L[a].push_back( make_pair(b,c) );
    }
    for(i=2;i<=n;i++){
        d[i]=dmax;
    }
    dh=h[1]=x[1]=1;
    while(dh){
        poz=h[1];
        del();
        for(i=0;i<L[poz].size();i++){
            a=L[poz][i].first;
            if( d[a] > d[poz] + L[poz][i].second ){
                ih=(d[a]!=dmax);
                d[a] = d[poz] + L[poz][i].second;
                if(!ih){
                    h[++dh]=a;
                    x[a]=dh;
                    upd(dh);
                }
                else
                    upd(x[a]);
            }
        }
    }
    for(i=2;i<=n;i++){
        if(d[i]==dmax)
            fprintf(g,"0 ");
        else
            fprintf(g,"%d ",d[i]);
    }
    fclose(f);
    fclose(g);
    return 0;
}