-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdijkstras_algorithm.cpp
132 lines (97 loc) · 2.62 KB
/
dijkstras_algorithm.cpp
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// Priority Queue Implementation
#include<bits/stdc++.h>
using namespace std;
#define INF INT_MAX
typedef pair<int, int> iPair;
void adjListGraph(vector<pair<int, int> > adj[], int s, int d, int w){
// undirected graph
adj[s].push_back({d, w});
adj[d].push_back({s, w});
}
void dijkstras(vector<pair<int, int> > adj[], int V, int src){
priority_queue<iPair, vector<iPair>, greater<iPair> > pq; // min heap
vector<int> dist(V, INF); // create a vector for distances and initialize all distances as infinite (INF)
pq.push({0, src});
dist[src]=0;
while(!pq.empty()){
int u=pq.top().second; // pair<distance, vertex >
pq.pop();
for(auto x: adj[u]){
int v=x.first; // pair<vertex, weight >
int w=x.second;
if(dist[v]>dist[u]+w){
dist[v]=dist[u]+w;
pq.push({dist[v], v});
}
}
}
cout<<endl;
cout<<"Vertex Distance"<<endl;
for(int i=0;i<V;i++){
cout<<i<<" "<<dist[i]<<endl;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int v,e;
cin>>v>>e;
vector<pair<int, int> > adj[v];
while(e--){
int s,d,w;
cin>>s>>d>>w;
adjListGraph(adj,s,d,w);
}
dijkstras(adj, v, 0); // source is 0
}
/*
Set implementation
#include<bits/stdc++.h>
using namespace std;
#define INF INT_MAX
typedef pair<int, int> iPair;
void adjListGraph(vector<pair<int, int> > adj[], int s, int d, int w){
// undirected graph
adj[s].push_back({d, w});
adj[d].push_back({s, w});
}
void dijkstras(vector<pair<int, int> > adj[], int V,int src){
set< pair<int, int> > s;
vector<int> dist(V, INF);
dist[src] = 0;
s.insert({dist[src], src});
while (!s.empty()){
pair<int, int> tmp = *(s.begin());
s.erase(s.begin());
int u = tmp.second;
for(auto it : adj[u]){
int v = it.first;
int w = it.second;
if(dist[v] > dist[u] + w){
if(dist[v] != INF)
s.erase(s.find({dist[v], v}));
dist[v] = dist[u] + w;
s.insert({dist[v], v});
}
}
}
cout<<endl;
cout<<"Vertex Distance"<<endl;
for(int i=0;i<V;i++){
cout<<i<<" "<<dist[i]<<endl;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int v,e;
cin>>v>>e;
vector<pair<int, int> > adj[v];
while(e--){
int s,d,w;
cin>>s>>d>>w;
adjListGraph(adj,s,d,w);
}
dijkstras(adj, v, 0); // source is 0
}
*/