有一块10000 * 10000 * 10000的立方体豆腐,
豆腐的前左下角放在(0,0,0)点,豆腐的后右上角放在(10000,10000,10000)点。
下面给出切法的数据结构:
[a,b],
a = 1,表示x = b处,一把无穷大的刀平行于yz面贯穿豆腐切过去;
a = 2,表示y = b处,一把无穷大的刀平行于xz面贯穿豆腐切过去;
a = 3,表示z = b处,一把无穷大的刀平行于xy面贯穿豆腐切过去;
a = 1 or 2 or 3,0<=b<=10000。
给定一个n*2的二维数组,表示切了n刀。
返回豆腐中最大的一块体积是多少?
这道题看起来很难,实际上很简单。
x最大长度y最大长度z最大长度。分别求x,y,z的最大长度,结果就能计算出来了。
代码用rust编写。代码如下:
fn main() {
let mut cuts: Vec<Vec<i32>> = vec![vec![1, 3000] , vec![2, 3], vec![3, 3]];
let ans = max_cut(&mut cuts);
println!("ans = {}", ans);
}
fn max_cut(cuts: &mut Vec<Vec<i32>>) -> i64 {
if cuts.len() == 0 {
return 10000 * 10000 * 10000;
}
// // 0 类型
// 1 切哪了
//Arrays.sort(cuts, (a, b) -> a[0] != b[0] ? (a[0] - b[0]) : (a[1] - b[1]));
cuts.sort_by(|a, b| {
if a[0] < b[0] {
std::cmp::Ordering::Less
} else if a[0] > b[0] {
std::cmp::Ordering::Greater
} else {
if a[1] < b[1] {
std::cmp::Ordering::Less
} else if a[1] > b[1] {
std::cmp::Ordering::Greater
} else {
std::cmp::Ordering::Equal
}
}
});
let n = cuts.len() as i32;
let mut i: i32 = 0;
let mut x_max_diff: i32 = 0;
let mut pre: i32 = 0;
while i < n && cuts[i as usize][0] == 1 {
x_max_diff = get_max(x_max_diff, cuts[i as usize][1] - pre);
pre = cuts[i as usize][1];
i += 1;
}
x_max_diff = get_max(x_max_diff, 10000 - pre);
let mut y_max_diff: i32 = 0;
pre = 0;
while i < n && cuts[i as usize][0] == 2 {
y_max_diff = get_max(y_max_diff, cuts[i as usize][1] - pre);
pre = cuts[i as usize][1];
i += 1;
}
y_max_diff = get_max(y_max_diff, 10000 - pre);
let mut z_max_diff: i32 = 0;
pre = 0;
while i < n && cuts[i as usize][0] == 3 {
z_max_diff = get_max(z_max_diff, cuts[i as usize][1] - pre);
pre = cuts[i as usize][1];
i += 1;
}
z_max_diff = get_max(z_max_diff, 10000 - pre);
return x_max_diff as i64 * y_max_diff as i64 * z_max_diff as i64;
}
fn get_max<T: Clone + Copy + std::cmp::PartialOrd>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
执行结果如下: