use std::collections::HashMap;
use std::hash::Hash;
use std::ops::{Add, Sub};
pub fn bellman_ford<T, W>(graph: &HashMap<T, Vec<(T, W)>>, start: T) -> Option<HashMap<T, W>>
where
T: Eq + Hash + Clone,
W: Copy + Ord + Default + Add<Output = W> + Sub<Output = W> + PartialOrd,
{
let mut dist = HashMap::new();
let nodes: Vec<_> = graph.keys().cloned().collect();
for node in &nodes {
dist.insert(node.clone(), W::default() + W::default() + W::default() + W::default() + W::default()); }
dist.insert(start.clone(), W::default());
for _ in 0..nodes.len() - 1 {
for (u, edges) in graph {
for (v, w) in edges {
let alt = dist[u] + *w;
if alt < dist[v] {
dist.insert(v.clone(), alt);
}
}
}
}
for (u, edges) in graph {
for (v, w) in edges {
if dist[u] + *w < dist[v] {
return None;
}
}
}
Some(dist)
}