-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshortest_path_faster_algorithm.cpp
More file actions
85 lines (73 loc) · 1.6 KB
/
shortest_path_faster_algorithm.cpp
File metadata and controls
85 lines (73 loc) · 1.6 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ar array
const int N = 1e5;
const int INF = INT_MAX;
vector<pair<int, int>> adj[N];
deque<int> q;
int dist[N];
int predecessor[N];
bool inqueue[N];
void shortest_path_faster_algorithm(int u, int n) {
for (int i = 1; i <= n; i++) dist[i] = INF;
dist[u] = 0;
q.push_back(u);
inqueue[u] = true;
predecessor[u] = -1;
while (!q.empty()) {
u = q.front(); q.pop_front();
inqueue[u] = false;
for (auto e : adj[u]) {
int a = u;
int b = e.first;
int w = e.second;
if (dist[a] + w < dist[b]) {
dist[b] = dist[a] + w;
predecessor[b] = a;
if (!inqueue[b]) {
q.push_back(b);
inqueue[b] = true;
if (q.back() < q.front()) {
int x = q.back(); q.pop_back();
q.push_front(x);
}
}
}
}
}
}
void reconstruct(int target) {
int current = target;
vector<int> path;
while (current != -1) {
path.insert(path.begin(), current);
current = predecessor[current];
}
string ans;
for (int x : path) {
ans += to_string(x) + " -> ";
}
for (int i = 1; i <= 4; i++) ans.pop_back();
cout << ans << "\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
adj[1].push_back({2, 5});
adj[1].push_back({3, 3});
adj[1].push_back({4, 7});
adj[3].push_back({4, 1});
adj[3].push_back({1, 3});
adj[2].push_back({1, 5});
adj[2].push_back({4, 3});
adj[2].push_back({5, 2});
adj[4].push_back({3, 1});
adj[4].push_back({1, 7});
adj[4].push_back({2, 3});
adj[4].push_back({5, 2});
adj[5].push_back({2, 2});
adj[5].push_back({4, 2});
shortest_path_faster_algorithm(1, 5);
reconstruct(5);
}