cp_library_rs/graph/
dijkstra.rs1use std::cmp::Reverse;
4use std::collections::BinaryHeap;
5
6use num_traits::{Bounded, Zero};
7
8#[allow(clippy::ptr_arg)]
15pub fn dijkstra<T: Copy + Zero + Bounded + Ord>(
16 graph: &Vec<Vec<(usize, T)>>,
17 s: usize,
18) -> (Vec<Option<usize>>, Vec<T>) {
19 let n: usize = graph.len();
20 let mut prev = vec![None; n];
21 let mut dist = vec![T::max_value(); n];
22 let mut pq: BinaryHeap<Reverse<(T, usize)>> = BinaryHeap::new();
23 dist[s] = T::zero();
25 pq.push(Reverse((dist[s], s)));
26 while let Some(Reverse((cost, u))) = pq.pop() {
28 if dist[u] < cost {
29 continue;
30 }
31 for &(v, weight) in &graph[u] {
32 if dist[v] > dist[u] + weight {
33 prev[v] = Some(u);
34 dist[v] = dist[u] + weight;
35 pq.push(Reverse((dist[v], v)));
36 }
37 }
38 }
39 (prev, dist)
40}
41
42#[allow(clippy::ptr_arg)]
49pub fn path_reconstruction(s: usize, t: usize, prev: &Vec<Option<usize>>) -> Option<Vec<usize>> {
50 if prev[s].is_some() || prev[t].is_none() {
51 return None;
52 }
53 let mut cur = t;
55 let mut path = vec![t];
56 while cur != s {
57 cur = prev[cur]?;
58 path.push(cur);
59 }
60 path.reverse();
61 Some(path)
62}