Pagini recente » Monitorul de evaluare | Cod sursa (job #1633379) | Cod sursa (job #2289434) | Cod sursa (job #1570431) | Cod sursa (job #1993700)
#include <bits/stdc++.h>
using namespace std;
#define DIM 10000
char buff[DIM];
int poz=0;
void cit(int &numar){
numar = 0;
while (buff[poz] < '0' || buff[poz] > '9')
if (++poz == DIM)
fread(buff,1,DIM,stdin),poz=0;
while ('0'<=buff[poz] && buff[poz]<='9'){
numar = numar*10 + buff[poz] - '0';
if (++poz == DIM)
fread(buff,1,DIM,stdin),poz=0;
}
}
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()
{
freopen("dijkstra.in","r",stdin);
freopen("dijkstra.out","w",stdout);
cit(n);cit(m);
for(int i = 1; i <= m; ++i){
cit(x);cit(y);cit(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)
printf("0 ");
else
printf("%d ",dist[i]);
}
return 0;
}