150403 二维数组的子矩阵最大和(动态规划)

最后课上,让我讲思路。

我一直尝试围绕上次一维的算法,模糊的概念讲不出来那是相当难受。

一维的那个的算法叫动态规划,二维一样可以用。

肯定是要以行或列写一个循环,然后将特定的列或行整体相加,按照一维的动态规划求最大一维子数组,间接得到最大子矩阵。

不止一个老师说过,要敢于质疑。我的观点,不可能做到O(n)。

//Powered by lzr!
#include<iostream> using namespace std; int yiwei_max(int n,int a[]) { int temp=0,sum=-999999999; for(int i=0;i<n;i++) { if(temp>0) { temp+=a[i]; } else { temp=a[i]; } if(temp>sum) { sum=temp; } } return sum; } void main() { int i,j,k,m,n; int a[100][100]; int b[100]; int temp=0,sum=-99999999; cout<<"几行几列?"<<endl; cin>>m>>n; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { cin>>a[i][j]; } } for(i=0;i<m;i++) { for(k=0;k<n;k++) { b[k]=0; } for(j=i;j<m;j++) { for(k=0;k<n;k++) { b[k]+=a[j][k]; } temp=yiwei_max(k,b); if(temp>sum) { sum=temp; } } } cout<<sum<<endl; }

原文地址:https://www.cnblogs.com/apak/p/4391195.html