Cod sursa(job #2126068)

Utilizator Horia14Horia Banciu Horia14 Data 9 februarie 2018 00:27:59
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include<cstdio>
#include<vector>
#define MAX_N 50000
#define oo 0x3f3f3f3f
using namespace std;

vector<pair<int,int>>g[MAX_N + 1];
int h[MAX_N + 1], pos[MAX_N + 1], dist[MAX_N + 1], n, m, k;

void readGraph() {
    int x, y, cost;
    FILE *fin = fopen("dijkstra.in","r");
    fscanf(fin,"%d%d",&n,&m);
    for(int i = 0; i < m; i++) {
        fscanf(fin,"%d%d%d",&x,&y,&cost);
        g[x].push_back(make_pair(y,cost));
    }
    fclose(fin);
}

inline 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;
}

inline void heapDown(int i) {
    int l, r;
    if(2*i > k) return;
    l = dist[h[2 * i]];
    if(2 * i + 1 <= k)
        r = dist[h[2 * i + 1]];
    else r = l + 1;
    if(l <= r) {
        if(dist[h[i]] <= l) return;
        Swap(i, 2 * i);
        heapDown(2 * i);
    } else {
        if(dist[h[i]] <= r) return;
        Swap(i, 2 * i + 1);
        heapDown(2 * i + 1);
    }
}

inline void heapUp(int i) {
    if(dist[h[i / 2]] <= dist[h[i]]) return;
    Swap(i, i / 2);
    heapUp(i / 2);
}

void Dijkstra(int source) {
    vector<pair<int,int>>::iterator it;
    int i, node;
    for(i = 1; i <= n; i++) {
        dist[i] = oo;
        h[i] = pos[i] = i;
    }
    dist[source] = 0;
    k = n;
    for(i = 1; i <= n; i++) {
        node = h[1];
        Swap(1,k);
        k--;
        heapDown(1);
        for(it = g[node].begin(); it != g[node].end(); it++) {
            if(dist[(*it).first] > dist[node] + (*it).second) {
                dist[(*it).first] = dist[node] + (*it).second;
                heapUp(pos[(*it).first]);
            }
        }
    }
}

void printDistances() {
    FILE *fout = fopen("dijkstra.out","w");
    for(int i = 2; i <= n; i++)
        if(dist[i] != oo)
            fprintf(fout,"%d ",dist[i]);
        else fprintf(fout,"0 ");
    fprintf(fout,"\n");
    fclose(fout);
}

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