From c05c2a8177ec1eb7386c92f82e2222efaf63aee2 Mon Sep 17 00:00:00 2001 From: EFanZh Date: Thu, 17 Oct 2024 22:06:38 +0800 Subject: [PATCH] Add problem 2285: Maximum Total Importance of Roads --- src/lib.rs | 1 + .../greedy.rs | 36 +++++++++++++++++++ .../mod.rs | 24 +++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 src/problem_2285_maximum_total_importance_of_roads/greedy.rs create mode 100644 src/problem_2285_maximum_total_importance_of_roads/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 69266e7f..5479210c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1694,6 +1694,7 @@ pub mod problem_2279_maximum_bags_with_full_capacity_of_rocks; pub mod problem_2280_minimum_lines_to_represent_a_line_chart; pub mod problem_2283_check_if_number_has_equal_digit_count_and_digit_value; pub mod problem_2284_sender_with_largest_word_count; +pub mod problem_2285_maximum_total_importance_of_roads; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2285_maximum_total_importance_of_roads/greedy.rs b/src/problem_2285_maximum_total_importance_of_roads/greedy.rs new file mode 100644 index 00000000..8778989b --- /dev/null +++ b/src/problem_2285_maximum_total_importance_of_roads/greedy.rs @@ -0,0 +1,36 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn maximum_importance(n: i32, roads: Vec>) -> i64 { + let mut degrees = vec![0_u16; n as u32 as usize]; + + for road in roads { + let [from, to] = <[_; 2]>::map(road.try_into().ok().unwrap(), |x| x as u32 as usize); + + degrees[from] += 1; + degrees[to] += 1; + } + + degrees.sort_unstable(); + + (1..).zip(degrees).map(|(i, x)| i * i64::from(x)).sum() + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn maximum_importance(n: i32, roads: Vec>) -> i64 { + Self::maximum_importance(n, roads) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2285_maximum_total_importance_of_roads/mod.rs b/src/problem_2285_maximum_total_importance_of_roads/mod.rs new file mode 100644 index 00000000..f46f816a --- /dev/null +++ b/src/problem_2285_maximum_total_importance_of_roads/mod.rs @@ -0,0 +1,24 @@ +pub mod greedy; + +pub trait Solution { + fn maximum_importance(n: i32, roads: Vec>) -> i64; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + ((5, &[[0, 1], [1, 2], [2, 3], [0, 2], [1, 3], [2, 4]] as &[_]), 43), + ((5, &[[0, 3], [2, 4], [1, 3]]), 20), + ]; + + for ((n, roads), expected) in test_cases { + assert_eq!( + S::maximum_importance(n, roads.iter().map(Vec::from).collect()), + expected, + ); + } + } +}