837. 新 21 点

This commit is contained in:
li-chx 2025-08-17 22:56:39 +08:00
parent bcc8fba011
commit da64b06ee9
1 changed files with 20 additions and 60 deletions

View File

@ -1,69 +1,29 @@
struct SegmentTree {
tree: Vec<i32>,
arr: Vec<i32>,
}
impl SegmentTree {
pub fn new(baskets: Vec<i32>) -> Self {
let n = baskets.len();
let size = 2 << (32 - (n as u32 - 1).leading_zeros());
let mut seg = SegmentTree {
tree: vec![0; size as usize],
arr: baskets.clone(),
};
seg.build(1, 0, n - 1);
seg
}
fn push_up(&mut self, o: usize) {
self.tree[o] = self.tree[o * 2].max(self.tree[o * 2 + 1]);
}
fn build(&mut self, o: usize, l: usize, r: usize) {
if l == r {
self.tree[o] = self.arr[l];
return;
}
let m = (l + r) / 2;
self.build(o * 2, l, m);
self.build(o * 2 + 1, m + 1, r);
self.push_up(o);
}
pub fn find_update(&mut self, o: usize, l: usize, r: usize, x: i32) -> Option<usize> {
if self.tree[o] < x {
return None;
}
if l == r {
self.tree[o] = -1;
return Some(l);
}
let m = (l + r) / 2;
let mut i = self.find_update(o * 2, l, m, x);
if i.is_none() {
i = self.find_update(o * 2 + 1, m + 1, r, x);
}
self.push_up(o);
i
}
}
struct Solution; struct Solution;
impl Solution { impl Solution {
pub fn num_of_unplaced_fruits( fruits: Vec<i32>, baskets: Vec<i32>) -> i32 { // return type: all situation, not crash situation
let n = baskets.len(); pub fn new21_game(n: i32, k: i32, max_pts: i32) -> f64 {
let mut tree = SegmentTree::new(baskets); let mut mem = vec![0f64; (k + max_pts + 1) as usize];
let mut ans = 0; for i in k .. k + max_pts + 1 {
mem[i as usize] = if i <= n { 1f64 } else { 0f64 };
for fruit in fruits.iter() {
if tree.find_update(1,0,n-1,*fruit).is_none() {
ans += 1;
} }
let mut temp_ans = 0f64;
if(k - 1 >= 0)
{
let i = k - 1;
for j in 1..max_pts + 1 {
temp_ans += mem[(i + j) as usize];
} }
ans mem[i as usize] = temp_ans as f64 / max_pts as f64;
}
for i in (0..k - 1).rev() {
temp_ans += mem[(i + 1) as usize] - mem[(i + max_pts + 1) as usize];
mem[i as usize] = temp_ans as f64 / max_pts as f64;
}
mem[0]
} }
} }
fn main() { fn main() {
let sl = Solution::num_of_unplaced_fruits(vec![4,2,5],vec![3,5,4]); let sl = Solution::new21_game(21, 17, 10);
println!("{:?}", sl); println!("{:?}", sl);
} }