Skip to content

Commit

Permalink
Add problem 0851: Loud and Rich
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Jun 28, 2024
1 parent 2bfcae4 commit c3b302a
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
56 changes: 56 additions & 0 deletions src/problem_0851_loud_and_rich/dfs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
pub struct Solution;

use std::collections::HashMap;

impl Solution {
pub fn loud_and_rich(richer: Vec<Vec<i32>>, quiet: Vec<i32>) -> Vec<i32> {
fn helper(
person: usize,
richer_map: &HashMap<usize, Vec<usize>>,
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::<usize, Vec<usize>>::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<Vec<i32>>, quiet: Vec<i32>) -> Vec<i32> {
Self::loud_and_rich(richer, quiet)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
27 changes: 27 additions & 0 deletions src/problem_0851_loud_and_rich/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
pub mod dfs;

pub trait Solution {
fn loud_and_rich(richer: Vec<Vec<i32>>, quiet: Vec<i32>) -> Vec<i32>;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
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
);
}
}
}

0 comments on commit c3b302a

Please sign in to comment.