Cod sursa(job #2191190)

Utilizator Horia14Horia Banciu Horia14 Data 1 aprilie 2018 22:55:24
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.45 kb
#include<cstdio>
#include<vector>
#include<cctype>
#define MAX_N 50000
#define BUF_SIZE 1 << 18
#define oo 0x3f3f3f3f
using namespace std;

vector<pair<int,int> >g[MAX_N + 1];
int dist[MAX_N + 1], h[MAX_N + 1], poz[MAX_N + 1], n, m, heapSize, pos = BUF_SIZE;
char buf[BUF_SIZE];

inline char getChar(FILE* fin) {
    if(pos == BUF_SIZE) {
        fread(buf,1,BUF_SIZE,fin);
        pos = 0;
    }
    return buf[pos++];
}

inline int read(FILE* fin) {
    int res = 0;
    char c;
    do {
        c = getChar(fin);
    }while(!isdigit(c));
    do {
        res = 10*res + c - '0';
        c = getChar(fin);
    }while(isdigit(c));
    return res;
}

void readGraph() {
    int x, y, cost;
    FILE* fin = fopen("dijkstra.in","r");
    n = read(fin);
    m = read(fin);
    for(int i = 0; i < m; i++) {
        x = read(fin);
        y = read(fin);
        cost = read(fin);
        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 = poz[h[i]];
    poz[h[i]] = poz[h[j]];
    poz[h[j]] = aux;
}

inline void heapDown(int i) {
    if(2*i > heapSize) return;
    int l, r;
    l = dist[h[2*i]];
    if(2*i + 1 <= heapSize)
        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 x) {
    int i, node;
    vector<pair<int,int> >::iterator it;
    for(i = 1; i <= n; i++) {
        dist[i] = oo;
        h[i] = poz[i] = i;
    }
    dist[x] = 0;
    heapSize = n;
    for(i = 1; i <= n; i++) {
        node = h[1];
        Swap(1,heapSize);
        heapSize--;
        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(poz[(*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;
}