-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDijkstra.cpp
More file actions
35 lines (28 loc) · 711 Bytes
/
Dijkstra.cpp
File metadata and controls
35 lines (28 loc) · 711 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
// Dijkstra
//
// Encontra o menor caminho do vértice de index s até os outros vértices
//
// O(n log(n))
const int INF = 0x3f3f3f3f;
vector<vector<pair<int, int>>> adj; // {to, weight}
int dijkstra(int n, int s) {
vector<int> dist(n, INF);
// origem
dist[s] = 0;
using pi = pair<int,int>;
priority_queue<pi, vector<pi>, greater<pi>> q;
q.emplace(0,s);
while (!q.empty()) {
auto [w,u] = q.top();
q.pop();
if (u == n-1) break;
if (w != dist[u]) continue;
for (auto [W,v] : adj[u]) {
if (w+W < dist[v]) {
dist[v] = w+W;
q.emplace(w+W,v);
}
}
}
return dist[n-1];
}