-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstra.cpp.txt
More file actions
49 lines (41 loc) · 1017 Bytes
/
Dijkstra.cpp.txt
File metadata and controls
49 lines (41 loc) · 1017 Bytes
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
#include<bits/stdc++.h>
using namespace std;
#define pi pair<int, int>
int main()
{
int n, e;
cin >> n >> e;
vector<pi>v[n+5];
while(e--)
{
int x, y, wt;
cin >> x >> y >> wt;
v[x].push_back({wt, y}); // x -> y (wt)
v[y].push_back({wt, x}); // Undirected
}
int src = 1;
vector<int>dis(n+5, INT_MAX);
dis[src] = 0;
priority_queue<pi, vector<pi>, greater<pi>>pq;
pq.push({0, src}); // {cost, node}
while(!pq.empty())
{
int cur_cost = pq.top().first;
int cur_node = pq.top().second;
pq.pop();
for(auto &adj: v[cur_node])
{
int wt = adj.first;
int to = adj.second;
if(dis[cur_node] + wt < dis[to])
{
dis[to] = dis[cur_node] + wt;
pq.push({dis[to], to});
}
}
}
for(int i=1; i<=n; i++)
{
cout << dis[i] << ' ';
}
}