Cod sursa(job #1933187)

Utilizator serbanSlincu Serban serban Data 20 martie 2017 15:36:37
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <bits/stdc++.h>
#define oo 2147483647

using namespace std;

vector< pair<int, int> > G[50005];
int d[50005];
int poz[50005];
bool viz[50005];
int heap[150005];
int lungime;

void urc(int i) {
    int tata = i / 2;
    while(tata > 0 && d[ heap[tata] ] > d[ heap[i] ]) {
            switch(heap[tata], heap[i]);
            switch(poz[tata], poz[i]);
            i = tata;
            tata /= 2;
    }
}

void scad(int i) {
    int son, ls, rs;
    do {
        son = 0;
        ls = i * 2;
        rs = i * 2 + 1;
        if(rs <= lungime) {
            if(d[ heap[ls] ] > d[ heap[rs] ]) son = rs;
            else son = ls;
        }
        else if(ls <= lungime) son = ls;
        if(son != 0 && d[ heap[son] ] < d[ heap[i] ]) {
            switch(heap[son], heap[i]);
            switch(poz[son], poz[i]);
        }
        else son = 0;
    }
    while(son != 0);
}

int scot() {
    int ret = heap[1];
    heap[1] = heap[lungime];
    poz[ret] = 0;
    lungime --;
    scad(1);
    return ret;
}

void bag(int i) {
    lungime ++;
    heap[lungime] = i;
    poz[i] = lungime;
    urc(lungime);
}


int main()
{
    ifstream f("dijkstra.in");
    ofstream g("dijkstra.out");

    int n, m, x, y, c;
    f >> n >> m;
    for(int i = 1; i <= m; i ++) {
        f >> x >> y >> c;
        G[x].push_back({y, c});
    }

    for(int i = 2; i <= n; i ++) d[i] = oo;

    bag(1);
    while(lungime > 0) {
        int nod = scot();

        for(auto j: G[nod]) {
            if(d[j.first] > d[nod] + j.second) {
                d[j.first] = d[nod] + j.second;
                if(!poz[j.first])
                    bag(j.first);
                else {
                    urc(poz[j.first]);
                    scad(poz[j.first]);
                }
            }
        }
    }

    for(int i = 2; i <= n; i ++) {
        if(d[i] == oo) g << "0 ";
        else g << d[i] << " ";
    }

    g << "\n";
    return 0;
}