Cod sursa(job #1993706)

Utilizator VladTiberiuMihailescu Vlad Tiberiu VladTiberiu Data 23 iunie 2017 16:47:52
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.47 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

const int NMax = 50003;
const int INF = (1 << 30);

class heap{
public:
    int Size;

    int minimum_value(){
        return heap[1].value;
    }
    int minimum_graph_node(){
        return heap[1].graph_node;
    }

    void insert_heap(int val,int graph_node){
        heap[++Size].value = val;
        heap[Size].graph_node = graph_node;
        go_up(Size);
    }
    void erase_heap(int node){
        swap(heap[node],heap[Size]);
        Size--;
        go_down(node);
    }
protected:
private:
    struct heap_stats{
        int value,graph_node;
    };

    heap_stats heap[NMax * 5];

    void go_up(int node){
        while(node > 1 && heap[node / 2].value > heap[node].value){
            swap(heap[node / 2], heap[node]);
            node /= 2;
        }
    }
    void go_down(int node){
        while((heap[node * 2].value < heap[node].value && node * 2 <= Size) ||
              (heap[node * 2 + 1].value < heap[node].value && node * 2 + 1 <= Size)){
            if(heap[node * 2].value < heap[node].value && node * 2 <= Size){
                swap(heap[node * 2], heap[node]);
                node *= 2;
            }else
            if(heap[node * 2 + 1].value < heap[node].value && node * 2 + 1 <= Size){
                swap(heap[node * 2 + 1],heap[node]);
                node = node * 2 + 1;
            }
        }
    }
};



int n,m,x,y,c;
int dist[NMax];
vector<pair<int,int> > G[NMax];

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

    for(int i = 1; i <= n; ++i){
        dist[i] = INF;
    }
    dist[1] = 0;

    heap H;
    H.insert_heap(0,1);

    while(H.Size){
        int current_distance = H.minimum_value();
        int current_node = H.minimum_graph_node();

        H.erase_heap(1);

        for(int i = 0; i < G[current_node].size(); ++i){
            int v = G[current_node][i].first;
            int cost = G[current_node][i].second;

            if(dist[v] > dist[current_node] + cost){
                dist[v] = dist[current_node] + cost;
                H.insert_heap(dist[v],v);
            }
        }
    }

    for(int i = 2; i <= n; ++i){
        if(dist[i] == INF)
            g << 0 << ' ';
        else
            g << dist[i] << ' ';
    }
    g << '\n';
    return 0;
}