Skip to content

Commit 6e7dd7a

Browse files
committed
Add problem 3376: Minimum Time to Break Locks I
1 parent 30c6591 commit 6e7dd7a

3 files changed

Lines changed: 74 additions & 0 deletions

File tree

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2208,6 +2208,7 @@ pub mod problem_3365_rearrange_k_substrings_to_form_target_string;
22082208
pub mod problem_3370_smallest_number_with_all_set_bits;
22092209
pub mod problem_3371_identify_the_largest_outlier_in_an_array;
22102210
pub mod problem_3375_minimum_operations_to_make_array_values_equal_to_k;
2211+
pub mod problem_3376_minimum_time_to_break_locks_i;
22112212

22122213
#[cfg(test)]
22132214
mod test_utilities;
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
fn iter_bits(mut x: u8, mut f: impl FnMut(u8)) {
7+
while x != 0 {
8+
let bit = x & x.wrapping_neg();
9+
10+
f(bit);
11+
12+
x ^= bit;
13+
}
14+
}
15+
16+
pub fn find_minimum_time(strength: Vec<i32>, k: i32) -> i32 {
17+
let strength = strength.into_iter().map(i32::cast_unsigned).collect::<Vec<_>>();
18+
let k = k.cast_unsigned();
19+
let cache = &mut [0_u32; 256][..1 << strength.len()];
20+
21+
for i in 1..cache.len() {
22+
let factor = 1 + k * (i.count_ones() - 1);
23+
let mut cost = u32::MAX;
24+
25+
Self::iter_bits(i as _, |bit| {
26+
cost = cost
27+
.min(cache[usize::from(i as u8 ^ bit)] + strength[bit.trailing_zeros() as usize].div_ceil(factor));
28+
});
29+
30+
cache[i] = cost;
31+
}
32+
33+
cache.last().unwrap().cast_signed()
34+
}
35+
}
36+
37+
// ------------------------------------------------------ snip ------------------------------------------------------ //
38+
39+
impl super::Solution for Solution {
40+
fn find_minimum_time(strength: Vec<i32>, k: i32) -> i32 {
41+
Self::find_minimum_time(strength, k)
42+
}
43+
}
44+
45+
#[cfg(test)]
46+
mod tests {
47+
#[test]
48+
fn test_solution() {
49+
super::super::tests::run::<super::Solution>();
50+
}
51+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
pub mod dynamic_programming;
2+
3+
pub trait Solution {
4+
fn find_minimum_time(strength: Vec<i32>, k: i32) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [
13+
((&[3, 4, 1] as &[_], 1), 4),
14+
((&[2, 5, 4], 2), 5),
15+
((&[25, 12, 21, 40, 20, 41, 14, 42], 4), 28),
16+
];
17+
18+
for ((strength, k), expected) in test_cases {
19+
assert_eq!(S::find_minimum_time(strength.to_vec(), k), expected);
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)