Anda di halaman 1dari 2

#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 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, poz;
l = 2 * i;
r = 2 * i + 1;
if(l <= heapSize && dist[h[l]] < dist[h[i]])
poz = l;
else poz = i;
if(r <= heapSize && dist[h[r]] < dist[h[poz]])
poz = r;
if(poz != i) {
Swap(i,poz);
heapDown(poz);
}
}

void heapUp(int i) {
if(dist[h[i]] < dist[h[i/2]]) {
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;
heapSize = n;
for(i = 0; i < n - 1; 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;
}

Anda mungkin juga menyukai