Last active
April 19, 2023 00:30
-
-
Save NamPE286/f0bd843d81170fa400b3085544989441 to your computer and use it in GitHub Desktop.
Dijkstra implementation in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
typedef long long ll; | |
struct item { | |
ll node; | |
ll weight; | |
bool operator<(const item &y) const { return weight > y.weight; } | |
}; | |
vector<ll> dijkstra(vector<vector<item>> &graph, ll n) { | |
vector<ll> dist(n + 1, LLONG_MAX); | |
dist[1] = 0; | |
priority_queue<item> pq; | |
pq.push({1, 0}); | |
while (!pq.empty()) { | |
item x = pq.top(); | |
pq.pop(); | |
if (x.weight != dist[x.node]) continue; | |
for (item i : graph[x.node]) { | |
if (x.weight + i.weight < dist[i.node]) { | |
dist[i.node] = x.weight + i.weight; | |
pq.push({i.node, x.weight + i.weight}); | |
} | |
} | |
} | |
return dist; | |
} | |
int main() { | |
ios::sync_with_stdio(0); | |
cout.tie(0); | |
cin.tie(0); | |
ll n, m; | |
cin >> n >> m; | |
vector<vector<item>> graph(n + 1); | |
while (m--) { | |
ll a, b, w; | |
cin >> a >> b >> w; | |
graph[a].push_back({b, w}); | |
} | |
vector<ll> dist = dijkstra(graph, n); | |
for (ll i = 1; i <= n; i++) { | |
cout << dist[i] << ' '; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment