Pagini recente » Cod sursa (job #2714977) | Cod sursa (job #2748528) | Cod sursa (job #2581370) | Cod sursa (job #918382) | Cod sursa (job #2209482)
#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 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;
}
void heapDown(int i) {
int dleftSon, drightSon;
if(2*i <= heapSize) {
dleftSon = dist[h[2*i]];
if(2*i+1 <= heapSize)
drightSon = dist[h[2*i+1]];
else drightSon = 1 + dleftSon;
if(dleftSon <= drightSon) {
if(dleftSon < dist[h[i]]) {
Swap(i,2*i);
heapDown(2*i);
}
} else {
if(drightSon < dist[h[i]]) {
Swap(i,2*i+1);
heapDown(2*i+1);
}
}
}
}
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;
Swap(1,source);
heapSize = n;
for(i = 1; i <= heapSize; 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,"0 ");
else fprintf(fout,"%d ",dist[i]);
fprintf(fout,"\n");
fclose(fout);
}
int main() {
readGraph();
Dijkstra(1);
printDistances();
return 0;
}