-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6.2 - Shortest path using Dijkstra algorithm.cpp
More file actions
62 lines (58 loc) · 1.6 KB
/
Copy path6.2 - Shortest path using Dijkstra algorithm.cpp
File metadata and controls
62 lines (58 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
//6.2 - Shortest path using Dijkstra algorithm
#include <bits/stdc++.h>
using namespace std;
#define MAX 100
int n, s, a[MAX][MAX], parent[MAX];
void Dijkstra(){
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int,int>>> pq;
vector<int> dist (n + 1, 1e9);
pq.push({0, s});
dist[s] = 0;
while(!pq.empty()){
auto top = pq.top();
pq.pop();
for(int i = 1; i <= n; i++){
if(a[top.second][i]){
if(top.first > dist[i]) continue;
if(dist[i] > dist[top.second] + a[top.second][i]){
dist[i] = dist[top.second] + a[top.second][i];
parent[i] = top.second;
pq.push({dist[i], i});
}
}
}
}
for(int i = 1; i <= n; i++){
cout << "K/c " << s << " -> " << i << " = ";
if(i == s){
cout << "0; " << s << " <- " << s << endl;
continue;
}
if(dist[i] == 1e9){
cout << "INF" << endl;
continue;
}
cout << dist[i] << "; ";
vector<int> path;
int j = i;
while(j != s){
path.push_back(j);
j = parent[j];
}
path.push_back(s);
for(int k = 0; k < path.size(); k++){
if(k == path.size() - 1){
cout << path[k] << endl;
continue;
}
cout << path[k] << " <- ";
}
}
}
int main(){
cin >> n >> s;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
cin >> a[i][j];
Dijkstra();
}