2419. 按位与最大的最长子数组

This commit is contained in:
li-chx 2025-07-30 10:59:42 +08:00
parent 99281d724c
commit 78f001bc32
1 changed files with 23 additions and 66 deletions

View File

@ -1,79 +1,36 @@
use std::ops::{AddAssign, SubAssign};
use std::cmp::max;
struct XorVal {
data: Vec<i32>,
count: usize,
}
impl XorVal {
pub fn new() -> Self {
XorVal { data: vec!(0; 32), count: 0 }
}
pub fn get_val(&self) -> i32 {
if self.count == 0 {
return -1;
}
let mut ans = 0;
for i in 0..32 {
if self.data[i] > 0 {
ans |= 1 << i;
}
}
ans
}
}
impl AddAssign<i32> for XorVal {
fn add_assign(&mut self, mut x: i32) {
self.count += 1;
let mut i = 0;
while x > 0 {
if x & 1 == 1 {
self.data[i] += 1;
}
x >>= 1;
i += 1;
}
}
}
impl SubAssign<i32> for XorVal {
fn sub_assign(&mut self, mut x: i32) {
self.count -= 1;
let mut i = 0;
while x > 0 {
if x & 1 == 1 {
self.data[i] -= 1;
}
x >>= 1;
i += 1;
}
}
}
struct Solution;
impl Solution {
pub fn smallest_subarrays(nums: Vec<i32>) -> Vec<i32> {
let mut ans = vec![0; nums.len()];
let mut xor = vec![0; nums.len()];
xor[nums.len() - 1] = nums[nums.len() - 1];
for i in (0..nums.len() - 1).rev() {
xor[i] = xor[i + 1] | nums[i];
}
let mut xor_val = XorVal::new();
let (mut l, mut r) = (0, 0);
pub fn longest_subarray(nums: Vec<i32>) -> i32 {
let mut ans = 0;
let mut ans_val = 0;
let mut last = 0;
let mut count = 0;
for i in 0..nums.len() {
while l < i && l <= r {
xor_val -= nums[l];
l += 1;
if nums[i] != last {
if ans_val < last {
ans_val = last;
ans = count;
}else if ans_val == last {
ans = max(count,ans);
}
last = nums[i];
count = 1;
} else {
count += 1;
}
while xor_val.get_val() < xor[i] {
xor_val += nums[r];
r += 1;
}
ans[i] = (r - l) as i32;
}
if ans_val < last {
ans = count;
}else if ans_val == last {
ans = max(count,ans);
}
ans
}
}
fn main() {
let sl = Solution::smallest_subarrays(vec![0]);
let sl = Solution::longest_subarray(vec![96317,96317,96317,96317,96317,96317,96317,96317,96317,279979]);
println!("{:?}", sl);
}