Pagini recente » Cod sursa (job #1380311) | Cod sursa (job #3223762) | Cod sursa (job #2559780) | Cod sursa (job #1930710) | Cod sursa (job #1164127)
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
struct edge {
int to, cost;
};
const int NMAX = 50005;
int N, M, dist[NMAX];
vector<struct edge*> edges[NMAX];
vector<int> heap;
void read() {
freopen("dijkstra.in", "r", stdin);
freopen("dijkstra.out", "w", stdout);
scanf("%d %d", &N, &M);
struct edge* new_edge;
int from;
for(int i = 1; i <= M; i++) {
new_edge = new struct edge;
scanf("%d%d%d", &from, &new_edge->to, &new_edge->cost);
edges[from].push_back(new_edge);
}
}
bool comp_heap(int a, int b) {
return dist[a] > dist[b];
}
void init() {
dist[1] = 0;
heap.push_back(1);
for(int i = 2; i <= N; i++) {
dist[i] = 1 << 30;
heap.push_back(i);
}
make_heap(heap.begin(), heap.end(), &comp_heap);
}
void solve() {
int cost, to;
while(!heap.empty()) {
pop_heap(heap.begin(), heap.end());
int v = heap.back();
heap.pop_back();
for(unsigned int i = 0; i < edges[v].size(); i++) {
to = edges[v][i]->to;
cost = edges[v][i]->cost;
if (dist[to] > cost + dist[v]) {
dist[to] = cost + dist[v];
make_heap(heap.begin(), heap.end(), &comp_heap);
}
}
}
}
void print() {
for(int i = 2; i <= N; i++)
printf("%d ", dist[i] == 1 << 30 ? 0 : dist[i]);
}
int main() {
read();
init();
solve();
print();
return 0;
}