Cod sursa(job #2216063)

Utilizator Horia14Horia Banciu Horia14 Data 24 iunie 2018 22:49:47
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
#include<cstdio>
#include<vector>
#define MAX_N 50000
#define oo 0x3f3f3f3f
using namespace std;

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

void readGraph() {
    int i, x, y, cost;
    FILE* fin = fopen("dijkstra.in","r");
    fscanf(fin,"%d%d",&n,&m);
    for(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 tmp = h[i];
    h[i] = h[j];
    h[j] = tmp;
    tmp = pos[h[i]];
    pos[h[i]] = pos[h[j]];
    pos[h[j]] = tmp;
}

void heapUp(int i) {
    if(dist[h[i/2]] > dist[h[i]]) {
        Swap(i,i/2);
        heapUp(i/2);
    }
}

void heapDown(int i) {
    int leftSon, rightSon;
    if(2*i <= heapSize) {
        leftSon = dist[h[2*i]];
        if(2*i + 1 <= heapSize)
            rightSon = dist[h[2*i+1]];
        else rightSon = 1 + leftSon;
        if(leftSon < rightSon) {
            if(dist[h[i]] > leftSon) {
                Swap(i,2*i);
                heapDown(2*i);
            }
        } else if(dist[h[i]] > rightSon) {
            Swap(i,2*i+1);
            heapDown(2*i+1);
        }
    }
}

void Dijkstra(int source) {
    int i, node;
    vector<pair<int,int> >::iterator it;
    for(i = 1; i <= n; i++) {
        dist[i] = oo;
        h[i] = pos[i] = i;
    }
    dist[source] = 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(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;
}