-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstra.cpp
More file actions
51 lines (46 loc) · 1.26 KB
/
Copy pathDijkstra.cpp
File metadata and controls
51 lines (46 loc) · 1.26 KB
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
template <class T = i64>
struct Dijkstra {
int n;
const T INF;
using pit = std::pair<int, T>;
using G = std::vector<std::vector<pit>>;
G g;
std::vector<int> parent;
Dijkstra(int n, const T& INF = 1e18) : n(n), g(n), INF(INF), parent(n, -1) {}
void add(int a, int b, T c) {
g[a].emplace_back(b, c);
}
std::vector<T> run(int s) {
std::vector<T> d(n, INF);
using pti = std::pair<T, int>;
std::priority_queue<pti, std::vector<pti>, std::greater<>> q;
d[s] = 0;
q.emplace(d[s], s);
while (q.size()) {
auto [dist, u] = q.top();
q.pop();
if (dist != d[u])
continue;
for (auto& [v, w] : g[u]) {
T fina = d[u] + w;
if (d[v] > fina) {
d[v] = fina;
parent[v] = u;
q.emplace(d[v], v);
}
}
}
return d;
}
std::vector<int> get_path(int t) {
std::vector<int> path;
for (; t != -1; t = parent[t]) {
path.push_back(t);
}
std::reverse(path.begin(), path.end());
return path;
}
bool has_path(int t) {
return parent[t] != -1;
}
};