forked from usamajay/hacktoberfest2021-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijkstra's algo.cpp
53 lines (44 loc) · 1.55 KB
/
Dijkstra's algo.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
//shortest path in undirected ugraph, using Dijkstra's algorithm
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m, source;
cin >> n >> m;
vector<pair<int, int>> g[n + 1]; // 1-indexed adjacency list for of graph
int a, b, wt;
for (int i = 0; i < m; i++)
{
cin >> a >> b >> wt;
g[a].push_back(make_pair(b, wt));
g[b].push_back(make_pair(a, wt));
}
cin >> source;
// Dijkstra's algorithm begins from here
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; // min-heap ; In pair => (dist,from)
vector<int> distance(n + 1, INT_MAX); // 1-indexed array for calculating shortest paths;
distance[source] = 0;
pq.push(make_pair(0, source)); // (dist,from)
while (!pq.empty())
{
int dist = pq.top().first;
int prev = pq.top().second;
pq.pop();
vector<pair<int, int>>::iterator it;
for (it = g[prev].begin(); it != g[prev].end(); it++)
{
int next = it->first;
int nextDist = it->second;
if (distance[next] > distance[prev] + nextDist)
{
distance[next] = distance[prev] + nextDist;
pq.push(make_pair(distance[next], next));
}
}
}
cout << "The distances from source, " << source << ", are : \n";
for (int i = 1; i <= n; i++)
cout << distance[i] << " ";
cout << "\n";
return 0;
}