Skip to content

Commit a83a56e

Browse files
authoredOct 5, 2022
Create Dijkstra's Algorithm
1 parent 15edf7a commit a83a56e

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
 

‎Dijkstra's Algorithm

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
#define debug(x) cout<<#x<<" is "<<endl
5+
6+
using ll = long long;
7+
8+
#define x first
9+
#define y second
10+
11+
template <typename T>
12+
struct Dijkstra {
13+
14+
int node,edge;
15+
vector< vector< pair<int,T> > > adj;
16+
vector< T > level;
17+
vector<int> parent;
18+
19+
Dijkstra(int _node, int _edge) : node(_node), edge(_edge) {
20+
vector<int>(node+1).swap(parent);
21+
vector<T>(node+1, numeric_limits<T>::max()).swap(level);
22+
vector< vector< pair<int,T> > > (node+1).swap(adj);
23+
}
24+
25+
void add_edge(int u, int v, T w) {
26+
adj[u].push_back({v,w});
27+
adj[v].push_back({u,w});
28+
}
29+
30+
void traverse(int src) {
31+
32+
level[src] = 0;
33+
set< pair<T,int> > s {{0,src}};
34+
parent[src] = -1;
35+
36+
while(not s.empty()) {
37+
auto it = *s.begin();
38+
int cur_node = it.y;
39+
T cur_level = it.x;
40+
s.erase(s.begin());
41+
42+
for(auto u : adj[cur_node]) {
43+
if(level[u.x] - u.y > cur_level) {
44+
level[u.x] = cur_level + u.y;
45+
parent[u.x] = cur_node;
46+
s.insert({level[u.x],u.x});
47+
}
48+
}
49+
}
50+
}
51+
52+
void print_path(int x) {
53+
54+
if(level[x] == numeric_limits<T>::max()) {
55+
cout<<"-1\n";
56+
return;
57+
}
58+
59+
if(x == -1){
60+
return;
61+
}
62+
63+
print_path(parent[x]);
64+
cout<<x<<" ";
65+
66+
}
67+
68+
};
69+
70+
71+
int main(int argc, char const *argv[])
72+
{
73+
ios::sync_with_stdio(false);
74+
cin.tie(nullptr);
75+
76+
77+
int node,edge;
78+
cin>>node>>edge;
79+
80+
Dijkstra<ll> d(node,edge);
81+
82+
83+
while(edge--){
84+
int x,y;
85+
ll w;
86+
cin>>x>>y>>w;
87+
d.add_edge(x,y,w);
88+
}
89+
90+
d.traverse(1);
91+
d.print_path(node);
92+
93+
return 0;
94+
}

0 commit comments

Comments
 (0)
Please sign in to comment.