蓝桥杯最大子矩阵c++
时间: 2023-10-10 19:11:59 浏览: 104
以下是一个求解最大子矩阵的C语言代码,使用动态规划算法:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_N 1000
int max(int a, int b) {
return a > b ? a : b;
}
int main() {
int n, m, a[MAX_N][MAX_N], f[MAX_N][MAX_N], ans = 0;
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &a[i][j]);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (j == 0) {
f[i][j] = a[i][j];
} else {
f[i][j] = a[i][j] ? f[i][j - 1] + 1 : 0;
}
}
}
for (int j = 0; j < m; j++) {
int h[MAX_N], stk[MAX_N], top = -1;
for (int i = 0; i < n; i++) {
h[i] = f[i][j];
while (top >= 0 && h[stk[top]] >= h[i]) {
int k = stk[top--];
int l = top >= 0 ? stk[top] : -1;
ans = max(ans, h[k] * (i - l - 1));
}
stk[++top] = i;
}
while (top >= 0) {
int k = stk[top--];
int l = top >= 0 ? stk[top] : -1;
ans = max(ans, h[k] * (n - l - 1));
}
}
printf("%d\n", ans);
return 0;
}
```
该算法的时间复杂度为$O(nm)$,空间复杂度为$O(nm)$。
阅读全文