-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijkstra
53 lines (46 loc) · 1.14 KB
/
dijkstra
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# -*- mode: snippet -*-
# name: dijkstra
# key: dijkstra
# --
using DistanceType = double;
const int MAX_V = 501 * 501; // TODO
const DistanceType INF = INT_MAX;
struct Edge {
int to;
DistanceType cost;
};
typedef pair<DistanceType, int> P; // firstは最短距離、secondは頂点の番号
int V; // 頂点数 TODO
vector<Edge> G[MAX_V]; // グラフ TODO
DistanceType d[MAX_V]; // 頂点sからの最短距離
int prev_[MAX_V]; // 最短路の直前の頂点
void dijkstra(int s) {
priority_queue<P, vector<P>, greater<P>> que;
fill(d, d + V, INF);
fill(prev_, prev_ + V, -1);
d[s] = 0;
que.push(P(0, s));
while (!que.empty()) {
P p = que.top();
que.pop();
int v = p.second;
if (d[v] < p.first)
continue;
for (int i = 0; i < (int)G[v].size(); i++) {
Edge e = G[v][i];
if (d[e.to] > d[v] + e.cost) {
d[e.to] = d[v] + e.cost;
prev_[e.to] = v;
que.push(P(d[e.to], e.to));
}
}
}
}
vector<int> get_path(int t) {
vector<int> path;
for (; t != -1; t = prev_[t]) {
path.push_back(t);
}
reverse(path.begin(), path.end());
return path;
}