题解 | #最大子矩阵#
最大子矩阵
https://www.nowcoder.com/practice/a5a0b05f0505406ca837a3a76a5419b3
#include<cstdio> #include<iostream> #include<climits> #define N 100 using namespace std; int com[N][N]; int total[N][N]; int dp[N]; int arr[N]; int MAXsub(int n){ int maxium = -INT_MAX ; for(int i = 0 ; i<n ; ++i){ if(i == 0){ dp[i] = arr[i]; }else{ dp[i] = max(arr[i] ,dp[i-1] + arr[i]); } maxium = max(maxium,dp[i]); } return maxium; } int Maxsubcom(int n){ int maximal = -INT_MAX; for(int i = 0 ; i < n ; ++i){ for(int j = i ; j < n ; ++j){ for(int k = 0 ; k < n ;++k ){ if( i ==0 ){ arr[k] = total[j][k]; }else{ arr[k] = total[j][k] - total[i-1][k]; } } int cur = MAXsub(n); maximal=max(maximal,cur); } } return maximal; } int main(){ int n ; while(scanf("%d",&n) != EOF){ for(int i = 0 ; i < n ; ++i){ for(int j = 0 ; j < n ; ++j){ scanf("%d",&com[i][j]); } } for(int i = 0 ; i < n ; ++i){ for(int j = 0 ; j < n ; ++j){ if(i == 0){ total[i][j] = com[i][j]; }else{ total[i][j] = total[i-1][j] + com[i][j];//压缩矩阵使矩阵变为一位total数组 } } } if( n == 1){ printf("%d\n",com[0][0]); }else{ int answer = Maxsubcom(n); printf("%d\n",answer); } } return 0; }