fn main() {
let mut arr = vec![1, 3, 1, 2];
let ans = total_strength(&mut arr);
println!("ans = {}", ans);
}
const mod0: i64 = 1000000007;
fn total_strength(arr: &mut Vec<i32>) -> i32 {
let n = arr.len() as i32;
let mut pre_sum = arr[0] as i64;
let mut sum_sum: Vec<i64> = vec![];
for _ in 0..n {
sum_sum.push(0);
}
sum_sum[0] = arr[0] as i64;
for i in 1..n {
pre_sum += arr[i as usize] as i64;
sum_sum[i as usize] = (sum_sum[(i - 1) as usize] + pre_sum) % mod0;
}
let mut stack: Vec<i32> = vec![];
for _ in 0..n {
stack.push(0);
}
let mut size: i32 = 0;
let mut ans: i64 = 0;
for i in 0..n {
while size > 0 && arr[stack[(size - 1) as usize] as usize] >= arr[i as usize] {
size -= 1;
let m = stack[size as usize];
let l = if size > 0 {
stack[(size - 1) as usize]
} else {
-1
};
// l(<当前值,且最近,到不了) m(当前数,做为最小值) i(<=当前数,到不了的!)
ans += magic_sum(arr, &mut sum_sum, l, m, i);
ans %= mod0;
}
stack[size as usize] = i;
size += 1;
}
while size > 0 {
size -= 1;
let m = stack[size as usize];
let l = if size > 0 {
stack[(size - 1) as usize]
} else {
-1
};
ans += magic_sum(arr, &mut sum_sum, l, m, n);
ans %= mod0;
}
ans as i32
}
fn magic_sum(arr: &mut Vec<i32>, sum_sum: &mut Vec<i64>, l: i32, m: i32, r: i32) -> i64 {
let left = (m as i64 - l as i64)
* (sum_sum[(r - 1) as usize]
- if m - 1 >= 0 {
sum_sum[(m - 1) as usize]
} else {
0
}
+ mod0)
% mod0;
let right = (r as i64 - m as i64)
* (if m - 1 >= 0 {
sum_sum[(m - 1) as usize]
} else {
0
} - if l - 1 >= 0 {
sum_sum[(l - 1) as usize]
} else {
0
} + mod0)
% mod0;
return arr[m as usize] as i64 * ((left - right + mod0) % mod0);
}
评论