Cod sursa(job #333902)

Utilizator levap1506Gutu Pavel levap1506 Data 24 iulie 2009 15:38:17
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
#include <fstream>
#include <iostream>
#include <vector>
#define maxn 50000
#define inf 123456789


using namespace std;

 int N,M, dist[maxn+100],poz[maxn+100], heap[maxn*5+100], hind, u,a ,b,c;
    vector<int> vecini[maxn],cost[maxn];
 vector<int>::iterator it,it1;

inline void swap(int i, int j){
int z;

    z=heap[i];
    heap[i]=heap[j];
    heap[j]=z;
    int t=poz[heap[i]];
    poz[heap[i]]=poz[heap[j]];
    poz[heap[j]]=t;

}
inline void upheap(int);
inline void add(int i) {
    heap[++hind]=i;
    upheap(hind);
    poz[i]=hind;
}
inline void downheap(int);
inline void dellete(int i) {
    swap(i,hind);
    poz[heap[hind]]=-1;
    //heap[hind]=0;
    hind--;
    downheap(i);
}
inline void upheap(int i) {
    while (i/2>0&&dist[heap[i]]<dist[heap[i/2]])
    {
        swap(i,i/2);
        i/=2;
    }
}
inline void downheap(int i) {
    while ((2*i<=hind&&dist[heap[i]]>dist[heap[2*i]])||(2*i+1<=hind&&dist[heap[i]]>dist[heap[2*i+1]]))
    {
        if (2*i+1<hind&&dist[heap[2*i+1]]<dist[heap[2*i]])
         {
             swap(2*i+1,i);
             i=2*i+1;
         }
         else
         {
             swap(2*i,i);
             i=2*i;
         }
    }
}
int main () {
    ifstream in;
    ofstream out;
    in.open("dijkstra.in");
    out.open("dijkstra.out");
    in >> N >> M;
    int i=0;
    for (i=0; i<M; i++) {
       in >> a >> b>>c;
       vecini[a].push_back(b);
       cost[a].push_back(c);
    }
    dist[1]=0;
    heap[1]=1;
    poz[1]=1;
    for (i=2; i<=N; i++)
    {
        dist[i]=inf;
        heap[i]=i;
        poz[i]=i;
    }
    hind=N;
    int v,alt;
    while (hind!=0) {
        u=heap[1];
       if (dist[u]==inf) break;
        dellete(1);

        for (it=vecini[u].begin(),it1=cost[u].begin();it!=vecini[u].end();it++,it1++) {
            v=*it;
            alt=dist[u]+*it1;
            if (alt<dist[v]) {
                dist[v]=alt;
                if (poz[v]>0) {
                     upheap(poz[v]);
                }
            }
        }
    }
    for (i=2; i<=N; i++)
    {
        if (dist[i]==inf) out << 0 << " ";else out << dist[i] << " ";
    }
    out.close();
    return 0;
}