3070. 元素和小于等于 k 的子矩阵的数目

This commit is contained in:
li_chx 2026-03-18 08:51:45 +08:00
parent 6c8fa06ce1
commit bb640829ee
Signed by: li_chx
GPG Key ID: 70D4985BB8180E92
1 changed files with 24 additions and 20 deletions

View File

@ -1,35 +1,39 @@
use std::cmp::max;
struct Solution; struct Solution;
mod arr; mod arr;
impl Solution { impl Solution {
pub fn largest_submatrix(mut matrix: Vec<Vec<i32>>) -> i32 { pub fn count_submatrices(mut grid: Vec<Vec<i32>>, k: i32) -> i32 {
for i in 1..matrix.len() { let mut ans = 0;
for j in 0..matrix[i].len() { if grid[0][0] <= k {
if matrix[i][j] == 1 { ans += 1;
matrix[i][j] = 1 + matrix[i - 1][j]; }else {
} return 0;
}
for i in 1..grid[0].len() {
grid[0][i] += grid[0][i-1];
if grid[0][i] <= k {
ans += 1;
} }
} }
let mut ans = 0; for i in 1.. grid.len() {
let mut arr = Vec::with_capacity(matrix[0].len()); grid[i][0] += grid[i-1][0];
for i in 0..matrix.len() { if grid[i][0] <= k {
for j in 0..matrix[i].len() { ans += 1;
arr.push(matrix[i][j]);
} }
arr.sort_unstable_by(|a, b| b.cmp(a)); for j in 1.. grid[i].len() {
for j in 0..matrix[i].len() { grid[i][j] += grid[i-1][j] + grid[i][j-1] - grid[i-1][j-1];
ans = max(ans, arr[j] * (j + 1) as i32); if grid[i][j] <= k {
ans += 1;
}
} }
arr.clear()
} }
ans ans
} }
} }
fn main() { fn main() {
let result = Solution::largest_submatrix(arr::make_matrix( let result = Solution::count_submatrices(arr::make_matrix(
"[[0,0,1],[1,1,1],[1,0,1]]", "[[7,2,9],[1,5,0],[2,6,6]]"
)); ), 20);
println!("{:?}", result); println!("{:?}", result);
} }