Cod sursa(job #853143)

Utilizator gabipurcaruGabi Purcaru gabipurcaru Data 12 ianuarie 2013 10:50:06
Problema Algoritmul lui Dijkstra Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <fstream>
#include <vector>
#include <utility>
using namespace std;

ifstream in("dijkstra.in");
ofstream out("dijkstra.out");

const int MAXN = 250010, INF = 1<<29;

int hn;
int n,m,a,b,c,costuri[MAXN];
bool viz[MAXN];
vector<pair<int, int> > g[MAXN];
pair<int, int> h[MAXN];

template<class T>
void push_heap(T val) {
    h[++hn] = val;
    int i = hn;
    while(i > 1 && h[i] < h[i/2]) {
        swap(h[i], h[i/2]);
        i /= 2;
    }
}

template<class T>
T pop_heap() {
    T ret = h[1],a,b;
    swap(h[1], h[hn--]);
    int i = 1;
    while(true) {
        if(2*i > hn)
            break;
        if(2*i+1 > hn) {
            if(h[i] > h[2*i])
                swap(h[i], h[2*i]);
            break;
        } else {
            if(h[i] > h[2*i]) {
                swap(h[i], h[2*i]);
                i *= 2;
            } else if(h[i] > h[2*i+1]) {
                swap(h[i], h[2*i+1]);
                i = 2*i+1;
            } else {
                break;
            }
        }
    }
    return ret;
}

void dijkstra(int nod) {
    push_heap(make_pair(0, nod));
    pair<int, int> tmp;
    int cost, i;
    while(hn) {
        tmp = pop_heap<pair<int, int> >();
        nod = tmp.second;
        if(viz[nod]) {
            continue;
        }
        cost = tmp.first;
        viz[nod] = true;
        for(i=0; i<g[nod].size(); ++i) {
            if(costuri[g[nod][i].first] > cost + g[nod][i].second) {
                push_heap(make_pair(cost + g[nod][i].second, g[nod][i].first));
                costuri[g[nod][i].first] = cost + g[nod][i].second;
            }
        }

    }
}

int main() {
    int i;
    in>>n>>m;
    for(i=1; i<=m; i++) {
        in>>a>>b>>c;
        g[a].push_back(make_pair(b, c));
    }
    for(i=1; i<=n; i++) {
        costuri[i] = INF;
    }
    costuri[1] = 0;
    dijkstra(1);
    for(i=2; i<=n; i++) {
        out<<(costuri[i] == INF ? 0 : costuri[i] )<<' ';
    }
    return 0;
}