diff --git a/src/lib.rs b/src/lib.rs index 59a099a..f6d386a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -415,6 +415,7 @@ pub mod problem_0841_keys_and_rooms; pub mod problem_0844_backspace_string_compare; pub mod problem_0845_longest_mountain_in_array; pub mod problem_0846_hand_of_straights; +pub mod problem_0851_loud_and_rich; pub mod problem_0859_buddy_strings; pub mod problem_0917_reverse_only_letters; pub mod problem_2348_number_of_zero_filled_subarrays; diff --git a/src/problem_0851_loud_and_rich/dfs.rs b/src/problem_0851_loud_and_rich/dfs.rs new file mode 100644 index 0000000..f2556de --- /dev/null +++ b/src/problem_0851_loud_and_rich/dfs.rs @@ -0,0 +1,56 @@ +pub struct Solution; + +use std::collections::HashMap; + +impl Solution { + pub fn loud_and_rich(richer: Vec>, quiet: Vec) -> Vec { + fn helper( + person: usize, + richer_map: &HashMap>, + quiet: &[i32], + result: &mut [i32], + ) -> (i32, usize) { + if result[person] != -1 { + let person = result[person] as usize; + return (quiet[person], person); + } + + let mut min = (quiet[person], person); + if let Some(richer) = richer_map.get(&person) { + for &person in richer { + let child = helper(person, richer_map, quiet, result); + min = min.min(child); + } + } + result[person] = min.1 as i32; + min + } + + let mut result = vec![-1; quiet.len()]; + let mut richer_map = HashMap::>::with_capacity(quiet.len()); + for richer in richer { + richer_map + .entry(richer[1] as usize) + .and_modify(|x| x.push(richer[0] as usize)) + .or_insert_with(|| vec![richer[0] as usize]); + } + for person in 0..quiet.len() { + helper(person, &richer_map, &quiet, &mut result); + } + result + } +} + +impl super::Solution for Solution { + fn loud_and_rich(richer: Vec>, quiet: Vec) -> Vec { + Self::loud_and_rich(richer, quiet) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_0851_loud_and_rich/mod.rs b/src/problem_0851_loud_and_rich/mod.rs new file mode 100644 index 0000000..d36d586 --- /dev/null +++ b/src/problem_0851_loud_and_rich/mod.rs @@ -0,0 +1,27 @@ +pub mod dfs; + +pub trait Solution { + fn loud_and_rich(richer: Vec>, quiet: Vec) -> Vec; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [( + ( + &[[1, 0], [2, 1], [3, 1], [3, 7], [4, 3], [5, 3], [6, 3]] as &[_], + &[3, 2, 5, 4, 6, 1, 7, 0] as &[_], + ), + &[5, 5, 2, 5, 4, 5, 6, 7] as &[_], + )]; + + for ((richer, quiet), expected) in test_cases { + assert_eq!( + S::loud_and_rich(richer.iter().map(Vec::from).collect(), quiet.to_vec()), + expected + ); + } + } +}