Cod sursa(job #1177809)

Utilizator lilian_ciobanuLilian Ciobanu lilian_ciobanu Data 26 aprilie 2014 13:34:31
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include<fstream>
#include<vector>

using namespace std;

ifstream f("traseu1.in");
ofstream g("traseu1.out");

const int INF=1000000000;

struct QQ{
    int nr;
    int cost;
};

vector<QQ> a[50005];
QQ h[2*50005];
bool viz[50005];
int drum[50005],nh=0;


void urca(int pos){
    QQ t=h[pos];

    while(pos>1 && h[pos].cost < h[pos/2].cost){
        t=h[pos];
        h[pos]=h[pos/2];
        h[pos/2]=t;
        pos/=2;
    }


}

void coboara(int pos){
    int ok=pos;
    QQ t;

    while(ok){
        ok=0;
        if(pos*2 <= nh)
            ok=pos*2;

        if(pos*2 +1 <=nh && h[ok].cost > h[pos*2+1].cost)
            ok++;

        if(h[ok].cost > h[pos].cost)
            ok=0;

        if(ok){
            t=h[ok];
            h[ok]=h[pos];
            h[pos]=t;
            pos=ok;
        }
    }
}


void insera(int x, int y){
    nh++;
    h[nh].nr=x;
    h[nh].cost=y;

    urca(nh);

}

void sterge(int pos){
    h[pos]=h[nh];
    nh--;

    if(pos>1 && h[pos].cost < h[pos/2].cost)
        urca(pos);
    else
        coboara(pos);

}





int main(){
    int n,m,s,e,i,j,x,y,z;

    f>>n>>m;

    QQ q;
    for(i=1; i<=m; ++i){
        f>>x>>y>>z;
        q.nr=y;
        q.cost=z;
        a[x].push_back(q);

        q.nr=x;
        a[y].push_back(q);

    }

   // f>>s>>e;

    for(i=1; i<=n; ++i){
        drum[i]=INF;
    }

    drum[1]=0;

    insera(1,0);


    int v,t,l;
    while(nh>0){
        v=h[1].nr;

        viz[v]=1;

        sterge(1);

        for(i=0; i<a[v].size(); ++i){
            t=a[v][i].nr;
            l=a[v][i].cost;

            if(!viz[t]){
            if(drum[t] > drum[v]+l)
                drum[t]=drum[v]+l;

                insera(t,drum[t]);
            }
        }
    }

   for(i=2; i<= n; ++i)
        if(drum[i]==INF)
            g<<"0 ";
        else
            g<<drum[i]<<' ';


return 0;
}