2022-05-27:现在有N条鱼,每条鱼的体积为Ai,从左到右排列,数组arr给出。 每一轮,左边的大鱼一定会吃掉右边比自己小的第一条鱼, 并且每条鱼吃比自己小的鱼的事件是同时发生的。 返回多少轮之后,鱼的数量会稳定。 注意:6 6 3 3。 第一轮过后 : 对于两个6来说,右边比自己小的第一条鱼都是第1个3,所以只有这个3被吃掉, 数组变成 : 6 6 3(第2个3), 第二轮过后 : 6 6。 返回2。 来自bilibili。
答案2022-05-27:
单调栈。
代码用rust编写。代码如下:
use rand::Rng;
fn main() {
let len: i32 = 50;
let value: i32 = 20;
let test_time: i32 = 20000;
println!("测试开始");
for _i in 0..test_time {
let n: i32 = rand::thread_rng().gen_range(0, len) + 1;
let mut arr = random_array(n, value);
let mut arr2 = arr.clone();
let ans1 = min_turns1(&mut arr);
let ans2 = min_turns2(&mut arr2);
if ans1 != ans2 {
println!("出错了!");
print!("arr = {:?}", arr);
println!("");
println!("ans1 = {}", ans1);
println!("ans2 = {}", ans2);
break;
}
}
println!("测试结束");
}
fn min_turns1(arr: &mut Vec<i32>) -> i32 {
let mut ans: i32 = 0;
loop {
let rest = eat_rest(arr);
if arr.len() == rest.len() {
break;
}
*arr = rest;
ans += 1;
}
return ans;
}
fn eat_rest(arr: &mut Vec<i32>) -> Vec<i32> {
if arr.len() == 0 {
return vec![0];
}
let n = arr.len() as i32;
let mut delete: Vec<bool> = vec![];
for _i in 0..n {
delete.push(false);
}
let mut len = n;
for i in 0..n {
for j in i + 1..n {
if arr[i as usize] > arr[j as usize] {
if !delete[j as usize] {
delete[j as usize] = true;
len -= 1;
}
break;
}
}
}
let mut rest: Vec<i32> = vec![];
for _i in 0..len {
rest.push(0);
}
let mut j: i32 = 0;
for i in 0..n {
if !delete[i as usize] {
rest[j as usize] = arr[i as usize];
j += 1;
}
}
return rest;
}
fn min_turns2(arr: &mut Vec<i32>) -> i32 {
let n = arr.len() as i32;
let mut stack: Vec<Vec<i32>> = vec![];
for i in 0..n {
stack.push(vec![]);
for _j in 0..2 {
stack[i as usize].push(0);
}
}
let mut stack_size: i32 = 0;
let mut ans = 0;
let mut i = n - 1;
while i >= 0 {
let mut cur_ans = 0;
while stack_size > 0 && stack[(stack_size - 1) as usize][0] < arr[i as usize] {
stack_size -= 1;
cur_ans = get_max(cur_ans + 1, stack[stack_size as usize][1]);
}
stack[stack_size as usize][0] = arr[i as usize];
stack[stack_size as usize][1] = cur_ans;
stack_size += 1;
ans = get_max(ans, cur_ans);
i -= 1;
}
return ans;
}
fn get_max<T: Clone + Copy + std::cmp::PartialOrd>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
// 为了测试
fn random_array(n: i32, v: i32) -> Vec<i32> {
let mut arr: Vec<i32> = vec![];
for _i in 0..n {
arr.push(rand::thread_rng().gen_range(0, v) - rand::thread_rng().gen_range(0, v));
}
return arr;
}
执行结果如下: