Pagini recente » Cod sursa (job #2561380) | Cod sursa (job #2655962) | Cod sursa (job #2117196) | Cod sursa (job #2147709) | Cod sursa (job #2242567)
#include<cstdio>
#include<vector>
#include<cctype>
#define MAX_N 50000
#define oo 0x3f3f3f3f
#define BUF_SIZE 1 << 18
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 ch;
do {
ch = getChar(fin);
}while(!isdigit(ch));
do {
res = 10*res + ch - '0';
ch = getChar(fin);
}while(isdigit(ch));
return res;
}
void readGraph() {
int x, y, c;
FILE* fin = fopen("dijkstra.in","r");
n = read(fin);
m = read(fin);
for(int i = 1; i <= m; i++) {
x = read(fin);
y = read(fin);
c = read(fin);
g[x].push_back(make_pair(y,c));
}
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;
}
void heapDown(int i) {
int l, r, p;
l = 2 * i;
r = 2 * i + 1;
if(l <= heapSize && dist[h[l]] < dist[h[i]])
p = l;
else p = i;
if(r <= heapSize && dist[h[r]] < dist[h[p]])
p = r;
if(p != i) {
Swap(i,p);
heapDown(p);
}
}
void heapUp(int i) {
while(dist[h[i]] < dist[h[i/2]]) {
Swap(i,i/2);
i >>= 1;
}
}
void Dijkstra(int s) {
int node;
for(int i = 1; i <= n; i++) {
dist[i] = oo;
h[i] = i;
poz[i] = i;
}
dist[s] = 0;
heapSize = n;
for(int j = 1; j <= n - 1; j++) {
node = h[1];
Swap(1,heapSize);
heapSize--;
heapDown(1);
for(auto i : g[node]) {
if(dist[i.first] > dist[node] + i.second) {
dist[i.first] = dist[node] + i.second;
heapUp(poz[i.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;
}