-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijkstra's-algorithm-sssp.cpp
74 lines (53 loc) · 1.36 KB
/
dijkstra's-algorithm-sssp.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
//Single Source shortest path!
#include <iostream>
#include <unordered_map>
#include <climits>
#include <list>
#include <vector>
#include <stack>
#include <cstring>
#include <queue>
using namespace std;
#define ll long long
#define INF 0x3f3f3f3f
void printutil(int n, vector<int> dist){
cout<<"Distance from source to vertex"<<endl;
for(int i=0; i<n; i++){
cout<<i<<" -> "<<dist[i]<<endl;
}
}
void getinput(int m, vector<pair<int,int>> al[]){
for(int i=0; i<m; i++){
int x,y,w; cin>>x>>y>>w;
al[x].push_back(make_pair(y, w));
al[y].push_back(make_pair(x, w));
}
}
bool solve(vector<pair<int,int>> al[], int k, int n){
priority_queue< pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>> > minhp;
vector<int> dist(n, INF);
dist[k]=0;
minhp.push(make_pair(0, k));
while(!minhp.empty()){
int u=minhp.top().second;
minhp.pop();
for(auto it: al[u]){
int v=it.first;
int w=it.second;
if(dist[v]>dist[u]+w){
dist[v]=dist[u]+w;
minhp.push(make_pair(dist[v], v));
}
}
}
printutil(n, dist);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n, m, k; cin>>n>>m>>k;
vector<pair<int, int>> al[n+1];
getinput(m, al);
solve(al, k, n);
return 0;
}