From 7f52800da164e7bb0d29a9b30f222b85d00698f0 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Mon, 11 Nov 2024 12:13:09 +0800 Subject: [PATCH] 20241111 finished. --- src/problem/mod.rs | 2 + .../p1547_minimum_cost_to_cut_a_stick.rs | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 src/problem/p1547_minimum_cost_to_cut_a_stick.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index d00e9a5..bd7de44 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -308,3 +308,5 @@ mod p3235_check_if_the_rectangle_corner_is_reachable; mod p3242_design_neighbor_sum_service; mod p540_single_element_in_a_sorted_array; + +mod p1547_minimum_cost_to_cut_a_stick; diff --git a/src/problem/p1547_minimum_cost_to_cut_a_stick.rs b/src/problem/p1547_minimum_cost_to_cut_a_stick.rs new file mode 100644 index 0000000..ffd72a2 --- /dev/null +++ b/src/problem/p1547_minimum_cost_to_cut_a_stick.rs @@ -0,0 +1,45 @@ +/** + * [1547] Minimum Cost to Cut a Stick + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn min_cost(n: i32, cuts: Vec) -> i32 { + let m = cuts.len(); + + let mut cuts = cuts; + cuts.sort_unstable(); + cuts.insert(0, 0); + cuts.push(n); + + let mut dp = vec![vec![0; m + 2]; m + 2]; + + for i in (1..=m).rev() { + for j in i..=m { + dp[i][j] = if i == j { 0 } else { i32::MAX }; + + for k in i..=j { + dp[i][j] = dp[i][j].min(dp[i][k - 1] + dp[k + 1][j]); + } + dp[i][j] += cuts[j + 1] - cuts[i - 1]; + } + } + + dp[1][m] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1547() { + assert_eq!(16, Solution::min_cost(7, vec![1, 3, 4, 5])); + assert_eq!(22, Solution::min_cost(9, vec![5, 6, 1, 4, 2])); + } +}