-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstras_algorithm.cpp
More file actions
72 lines (65 loc) · 1.48 KB
/
dijkstras_algorithm.cpp
File metadata and controls
72 lines (65 loc) · 1.48 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
#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];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
bool vis[N];
int predecessor[N];
int dist[N];
void dijkstras_algorithm(int u, int n) {
for (int i = 1; i <= n; i++) dist[i] = INF;
dist[u] = 0;
predecessor[u] = -1;
q.push({0, u});
while (!q.empty()) {
int u = q.top().second; q.pop();
if (!vis[u]) {
vis[u] = true;
for (auto v : adj[u]) {
int b = v.first, w = v.second;
if (dist[u] + w < dist[b]) {
dist[b] = dist[u] + w;
predecessor[b] = u;
q.push({dist[b], b});
}
}
}
}
}
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});
dijkstras_algorithm(1, 5);
reconstruct(5);
}