with priority queue
| 66 | |
| 67 | // with priority queue |
| 68 | void dijstra2(vector<pair<int, int>> vec[], int v, int source) |
| 69 | { |
| 70 | vector<int> dist(v, INT_MAX); |
| 71 | vector<bool> mst(v, false); |
| 72 | |
| 73 | dist[source] = 0; |
| 74 | priority_queue<pair<int, int>, vector<pair<int, int>>, mycmp> pq; |
| 75 | pq.push({source, 0}); |
| 76 | |
| 77 | for (int i = 0; i < v; i++) |
| 78 | { |
| 79 | while (pq.empty() == false && mst[pq.top().first] == true) |
| 80 | { |
| 81 | pq.pop(); |
| 82 | } |
| 83 | |
| 84 | pair<int, int> curr = pq.top(); |
| 85 | pq.pop(); |
| 86 | |
| 87 | for (int j = 0; j < vec[curr.first].size(); j++) |
| 88 | { |
| 89 | int adjacent = vec[curr.first][j].first; |
| 90 | int adj_weight = vec[curr.first][j].second; |
| 91 | |
| 92 | if (mst[adjacent] == false && dist[adjacent] > dist[curr.first] + adj_weight) |
| 93 | { |
| 94 | dist[adjacent] = dist[curr.first] + adj_weight; |
| 95 | pq.push({adjacent, dist[adjacent]}); |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | cout << "Minimum distances(priority queue) are: " << endl; |
| 100 | for (int i = 0; i < dist.size(); i++) |
| 101 | { |
| 102 | cout << dist[i] << " "; |
| 103 | } |
| 104 | cout << endl; |
| 105 | } |
| 106 | |
| 107 | int main() |
| 108 | { |