topic
answer
Violence to solve
Range of topics , violence can be directly solved the biggest sub-matrix. Complexity , this complexity is generally acceptable.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define maxn 105
#define inf 0x3f3f3f3f
int n, ans;
int f[maxn][maxn], a[maxn][maxn];
int _max(int a, int b){
return a > b ? a : b;
}
int main()
{
scanf("%d", &n);
ans = -inf;
int i, j, k, l;
for(i = 1; i <= n; i++){
for(j = 1; j <= n; j++){
scanf("%d", &a[i][j]);
f[i][j] = f[i - 1][j] + f[i][j - 1] - f[i - 1][j - 1] + a[i][j];
}
}
for(i = 1; i <= n; i++){
for(j = 1; j <= n; j++){
for(k = i; k <= n; k++){
for(l = j; l <= n; l++){
ans = _max(ans, f[k][l] - f[k][j - 1] - f[i - 1][l] + f[i - 1][j - 1]);
}
}
}
}
printf("%d\n", ans);
return 0;
}
dp solving
- means that for the first column before matrix of rows and prefix. which is 。
- represents the starting line number , end line numbers sub-matrices, the first sub-matrix and elements of the column.
Using a similar method to solve the maximum continuous substring is solved. The resulting sub-matrix is the maximum, the complexity of 。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define maxn 105
#define inf 0x3f3f3f3f
int n, ans;
int pre[maxn][maxn], a[maxn][maxn], f[maxn];
int _max(int a, int b){
return a > b ? a : b;
}
int main()
{
scanf("%d", &n);
ans = -inf;
int i, j, k;
for(i = 1; i <= n; i++){
for(j = 1; j <= n; j++){
scanf("%d", &a[i][j]);
pre[i][j] = pre[i - 1][j] + a[i][j];
}
}
for(i = 1; i <= n; i++){
for(j = i + 1; j <= n; j++){
for(k = 1; k <= n; k++){
f[k] = pre[j][k] - pre[i - 1][k];
}
for(k = 1; k <= n; k++){
f[k] = _max(f[k - 1] + f[k], f[k]);
ans = _max(ans, f[k]);
}
}
}
printf("%d\n", ans);
return 0;
}