From 2d191e4d62ba57d09e500f6aad8a5484d72c696b Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 16 Aug 2024 11:45:00 +0800 Subject: [PATCH] 20240816 Finished --- src/problem/mod.rs | 3 +- ...minimum_sum_of_values_by_dividing_array.rs | 65 +++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 src/problem/p3117_minimum_sum_of_values_by_dividing_array.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index c672abc..d1d3a79 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -205,4 +205,5 @@ mod p97_interleaving_string; mod p72_edit_distance; mod p123_best_time_to_buy_and_sell_stock_iii; mod p188_best_time_to_buy_and_sell_stock_iv; -mod p221_maximal_square; \ No newline at end of file +mod p221_maximal_square; +mod p3117_minimum_sum_of_values_by_dividing_array; \ No newline at end of file diff --git a/src/problem/p3117_minimum_sum_of_values_by_dividing_array.rs b/src/problem/p3117_minimum_sum_of_values_by_dividing_array.rs new file mode 100644 index 0000000..bdb372d --- /dev/null +++ b/src/problem/p3117_minimum_sum_of_values_by_dividing_array.rs @@ -0,0 +1,65 @@ +/** + * [3117] Minimum Sum of Values by Dividing Array + */ +pub struct Solution {} + + +// submission codes start here +use std::collections::HashMap; + +const INFINITE: i32 = (1 << 20) - 1; + +impl Solution { + pub fn minimum_value_sum(nums: Vec, and_values: Vec) -> i32 { + let (n, m) = (nums.len(), and_values.len()); + let mut memory = vec![HashMap::new(); m * n]; + + let result = Self::dfs(&mut memory, 0, 0, INFINITE, &nums, &and_values); + if result == INFINITE { + -1 + } else { + result + } + } + + fn dfs(memory: &mut Vec>, i: usize, j: usize, current: i32, + nums: &Vec, and_values: &Vec) -> i32 { + let (n, m) = (nums.len(), and_values.len()); + let key = m * i + j; + + if i == n && j == m { + return 0; + } + if i == n || j == m { + return INFINITE; + } + if let Some(r) = memory[key].get(¤t) { + return *r; + } + + let current = current & nums[i]; + if current & and_values[j] < and_values[j] { + return INFINITE; + } + + let mut result = Self::dfs(memory, i + 1, j, current, nums, and_values); + if current == and_values[j] { + result = result.min(Self::dfs(memory, i + 1, j + 1, INFINITE, nums, and_values) + nums[i]); + } + + memory[key].insert(current, result); + return result; + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3117() { + assert_eq!(12, Solution::minimum_value_sum(vec![1, 4, 3, 3, 2], vec![0, 3, 3, 2])); + } +}