Cod sursa(job #2546865)

Utilizator Horia14Horia Banciu Horia14 Data 14 februarie 2020 17:41:50
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include<fstream>
#include<iostream>
#include<vector>
#define MAX_V 50000
#define oo 0x3f3f3f3f
using namespace std;

vector<pair<int, int>>g[MAX_V + 1];
int dmin[MAX_V + 1], h[MAX_V + 1], pos[MAX_V + 1], n, m, heapSize;

void readGraph() {
    int x, y, c;
    ifstream fin("dijkstra.in");
    fin >> n >> m;
    for(int i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        g[x].push_back({y, c});
    }
    fin.close();
}

void Swap(int i, int j) {
    int aux = h[i];
    h[i] = h[j];
    h[j] = aux;
    aux = pos[h[i]];
    pos[h[i]] = pos[h[j]];
    pos[h[j]] = aux;
}

void heapDown(int i) {
    int l, r, p;
    l = 2 * i;
    r = 2 * i + 1;
    if(l <= heapSize && dmin[h[l]] < dmin[h[i]])
        p = l;
    else p = i;
    if(r <= heapSize && dmin[h[r]] < dmin[h[p]])
        p = r;
    if(p != i) {
        Swap(p, i);
        heapDown(p);
    }
}

void heapUp(int i) {
    while(dmin[h[i/2]] > dmin[h[i]]) {
        Swap(i, i / 2);
        i >>= 1;
    }
}

void Dijkstra(int source) {
    int node;
    for(int i = 1; i <= n; i++) {
        dmin[i] = oo;
        h[i] = pos[i] = i;
    }
    dmin[source] = 0;
    Swap(1, source);
    heapSize = n;
    for(int i = 1; i <= n - 1; i++) {
        node = h[1];
        Swap(1, heapSize);
        heapSize--;
        heapDown(1);
        for(auto j : g[node]) {
            if(dmin[j.first] > dmin[node] + j.second) {
                dmin[j.first] = dmin[node] + j.second;
                heapUp(pos[j.first]);
            }
        }
    }
}

void printDistances() {
    ofstream fout("dijkstra.out");
    for(int i = 2; i <= n; i++) {
        if(dmin[i] == oo)
            fout << "0 ";
        else fout << dmin[i] << " ";
    }
    fout << "\n";
    fout.close();
}

int main() {
    readGraph();
    Dijkstra(1);
    printDistances();
    return 0;
}