Pagini recente » Teoria jocurilor: numerele Sprague Grundy | Cod sursa (job #1112864) | Istoria paginii runda/test12321321 | Autentificare | Cod sursa (job #2013431)
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
const int MAX = (5e5 + 5);
const int INF = (1e9);
template < class Type >
class Heap {
public:
Heap(): _MAX(MAX) {
this -> _arr.resize(_MAX);
this -> _heap.resize(_MAX);
this -> _arr_size = 0;
this -> _heap_size = 0;
}
bool empty() {
return _heap_size == 0;
}
int size() {
return _heap_size;
}
Type push(Type x) {
_push(x);
}
Type pop() {
_pop();
}
Type top() {
return _arr[_heap[1]];
}
private:
const int _MAX;
vector < int > _heap;
vector < Type > _arr;
int _heap_size;
int _arr_size;
void _repair(int node) {
if ((node << 1 | 1) <= _heap_size) {
if (_arr[_heap[node]] > min(_arr[_heap[node << 1]], _arr[_heap[node << 1 | 1]])) {
if (_arr[_heap[node << 1]] <= _arr[_heap[node << 1 | 1]]) {
swap(_heap[node], _heap[node << 1]);
_repair(node << 1);
}
else {
swap(_heap[node], _heap[node << 1 | 1]);
_repair(node << 1 | 1);
}
}
return;
}
else if ((node << 1) == _heap_size) {
if (_arr[_heap[node]] > _arr[_heap[node << 1]]) {
swap(_heap[node], _heap[node << 1]);
}
return;
}
else if (node << 1 > _heap_size) {
return;
}
}
void _pop() {
swap(this -> _heap[1], this -> _heap[this -> _heap_size --]);
this -> _repair(1);
}
void _set_poz(int node) {
if (_arr[_heap[node]] >= _arr[_heap[node >> 1]] or node == 1) {
return;
}
swap(_heap[node], _heap[node >> 1]);
_set_poz(node >> 1);
}
void _push(Type x) {
_arr[++ _arr_size] = x;
_heap[++ _heap_size] = _arr_size;
_set_poz(_heap_size);
}
};
int main() {
Heap < pair < int, int > > *h = new Heap < pair < int, int > > ();
vector < vector < pair < int, int > > > node(MAX);
vector < int > dist(MAX, INF);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i ++) {
int a, b, cost;
cin >> a >> b >> cost;
node[a].push_back({b, cost});
node[b].push_back({a, cost});
}
for (int i = 1; i <= n; i ++) {
if (!node[i].size()) continue;
h -> push({i, 0});
dist[i] = 0;
break;
}
while (!h -> empty()) {
pair < int, int > cur = h -> top();
int cur_node = cur.first;
int cur_dist = cur.second;
h -> pop();
if (dist[cur_node] != cur_dist) {
continue;
}
for (int i = 0; i < node[cur_node].size(); i ++) {
pair < int, int > neigh_node = node[cur_node][i];
int dist_to = cur_dist + neigh_node.second;
if (dist_to < dist[neigh_node.first]) {
dist[neigh_node.first] = dist_to;
h -> push(neigh_node);
}
}
}
for (int i = 2; i <= n; i ++) {
if (dist[i] == INF)
cout << 0 << ' ';
else
cout << dist[i] << ' ';
}
cout << '\n';
}