Skip to content

Commit

Permalink
Add problem 2285: Maximum Total Importance of Roads
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Oct 17, 2024
1 parent 80d357c commit c05c2a8
Show file tree
Hide file tree
Showing 3 changed files with 61 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 @@ -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;
36 changes: 36 additions & 0 deletions src/problem_2285_maximum_total_importance_of_roads/greedy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn maximum_importance(n: i32, roads: Vec<Vec<i32>>) -> 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<Vec<i32>>) -> i64 {
Self::maximum_importance(n, roads)
}
}

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

pub trait Solution {
fn maximum_importance(n: i32, roads: Vec<Vec<i32>>) -> i64;
}

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

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

0 comments on commit c05c2a8

Please sign in to comment.