use std::collections::{HashMap, BinaryHeap};
use std::cmp::Reverse;
use std::ops::Add;
pub fn dijkstra<T, W>(graph: &HashMap<T, Vec<(T, W)>>, start: T) -> HashMap<T, W>
where
T: Eq + std::hash::Hash + Clone + Ord,
W: Copy + Ord + Default + Add<Output = W>,
{
let mut dist = HashMap::new();
let mut heap = BinaryHeap::new();
dist.insert(start.clone(), W::default());
heap.push(Reverse((W::default(), start.clone())));
while let Some(Reverse((cost, node))) = heap.pop() {
if let Some(neighbors) = graph.get(&node) {
for (neighbor, weight) in neighbors {
let next = cost + *weight;
if dist.get(neighbor).map_or(true, |&d| next < d) {
dist.insert(neighbor.clone(), next);
heap.push(Reverse((next, neighbor.clone())));
}
}
}
}
dist
}