Cod sursa(job #1613381)

Utilizator VicktorVictor Teodor Stoian Vicktor Data 25 februarie 2016 12:56:41
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <fstream>
#define inf 1<<30

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
 struct graf{
    int info,c;
        graf *urm;
 }*v[10000];

 int n,m,cost[10000],h[10000],poz[10000],k;
 void add(int x, int y, int c){
 graf *p=new graf;
 p->c=c;
 p->info=y;
 p->urm=v[x];
 v[x]=p;
 p=new graf;
 p->c=c;
 p->info=x;
 p->urm=v[y];
 v[y]=p;
 }
void citire(){
    fin>>n>>m;
    int x,y,c;
    for(int i=1;i<=m;i++){
        fin>>x>>y>>c;
        add(x,y,c);
    }
    for(int i=1;i<=n;i++){
        cost[i]=inf, poz[i]=-1;
    }
}
inline void swap(int x, int y){
    int aux;
    poz[h[x]]=y;
    poz[h[y]]=x;
    aux=h[x];
    h[x]=h[y];
    h[y]=aux;
}
void heapup(int x){
    int tata;
    if(x>1){
        tata=x>>1;
        if(cost[h[tata]]>cost[h[x]]){
            swap(x,tata);
            heapup(tata);
        }
    }
}
void heapdown(int x){
    int fiu;
    if(x<=k>>1){
        if(x<k>>1){
            fiu=(x<<1)+1;
            if(cost[h[fiu]]<cost[h[x]]){
                swap(fiu,x);
                heapdown(fiu);
            }
        }
        else{
             fiu=x<<1;
            if(cost[h[fiu]]<cost[h[x]]){
                swap(fiu,x);
                heapdown(fiu);
            }
        }
    }
}
void dijkstra(){
    graf *p;
    int nod;
    poz[1]=1;
    cost[1]=0;
    h[++k]=1;
    while(k){
        nod=h[1];
        swap(1,k); k--;
        poz[h[1]]=1;
        heapdown(1);
        for(p=v[nod];p;p=p->urm)
            if(cost[p->info]>cost[nod]+p->c){
                cost[p->info]=cost[nod]+p->c;
                if(poz[p->info]!=-1)
                    heapup(poz[p->info]);
                else{
                    h[++k]=p->info;
                    poz[h[k]]=k;
                    heapup(k);
                }
            }
    }
}
int main(){
citire();
dijkstra();
for(int i=2;i<=n;i++)
    fout<<(cost[i]==inf ? 0 : cost[i])<<' ';
}