Pagini recente » Cod sursa (job #2457788) | Cod sursa (job #1244698) | Cod sursa (job #2542076) | Cod sursa (job #1570747) | Cod sursa (job #1993698)
#include <bits/stdc++.h>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
const int NMax = 50003;
const int INF = (1 << 30);
struct heap_stats{
int value,graph_node;
};
heap_stats heap[NMax * 5];
int Size;
void go_up(int node){
while(node > 1 && heap[node / 2].value > heap[node].value){
swap(heap[node / 2], heap[node]);
node /= 2;
}
}
void go_down(int node){
while((heap[node * 2].value < heap[node].value && node * 2 <= Size) ||
(heap[node * 2 + 1].value < heap[node].value && node * 2 + 1 <= Size)){
if(heap[node * 2].value < heap[node].value && node * 2 <= Size){
swap(heap[node * 2], heap[node]);
node *= 2;
}else
if(heap[node * 2 + 1].value < heap[node].value && node * 2 + 1 <= Size){
swap(heap[node * 2 + 1],heap[node]);
node = node * 2 + 1;
}
}
}
void insert_heap(int val,int graph_node){
heap[++Size].value = val;
heap[Size].graph_node = graph_node;
go_up(Size);
}
void erase_heap(int node){
swap(heap[node],heap[Size]);
Size--;
go_down(node);
}
int n,m,x,y,c;
int dist[NMax];
vector<pair<int,int> > G[NMax];
int main()
{
f >> n >> m;
for(int i = 1; i <= m; ++i){
f >> x >> y >> c;
G[x].push_back(make_pair(y,c));
}
for(int i = 1; i <= n; ++i){
dist[i] = INF;
}
dist[1] = 0;
insert_heap(0,1);
while(Size){
int current_distance = heap[1].value;
int current_node = heap[1].graph_node;
erase_heap(1);
for(int i = 0; i < G[current_node].size(); ++i){
int v = G[current_node][i].first;
int cost = G[current_node][i].second;
if(dist[v] > dist[current_node] + cost){
dist[v] = dist[current_node] + cost;
insert_heap(dist[v],v);
}
}
}
for(int i = 2; i <= n; ++i){
if(dist[i] == INF)
g << 0 << ' ';
else
g << dist[i] << ' ';
}
g << '\n';
return 0;
}