POJ1050
题意:给定一个NN的矩阵,在矩阵中寻找一个hw的矩阵,使得对于所有可能的矩阵,这个矩阵的所有元素和最大,并输出这个最大值。
ex:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
最大子矩阵为
9 2
-4 1
-1 8
和15
思路:求出所有ⅰ到j行的最大子矩阵和,并记录最大值,ⅰ到j行的最大子矩阵和分两步,先将ⅰ到j行压缩为一维数组,对这个一维数组求最大连读子序列和
代码
#include<iostream>
#include<cstring>
#define N 105
using namespace std;
int a[N+1][N+1];
int n;
int main(){
cin >> n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
scanf("%d", &a[i][j]);
}
}
int max = a[1][1];
int temp[N];
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
temp[j] = 0;
}
for(int j = i; j <= n; j++){
//ⅰ到j行的K列和t数组
for(int k = 1; k <= n; k++){
temp[k] += a[j][k];
}
//====求最大ⅰ到j行最大子矩阵=通过t数组求最大连续子续列和
int tempMax = 0, sum = 0;
for(int k = 1; k <= n; k++){
if(sum > 0){
sum += temp[k];
}else{
sum = temp[k];
}
if(sum > tempMax){
tempMax = sum;
}
}
//记录ⅰ到j行最大子矩阵和,并比较记录最大值,当所有ⅰ,j行的最大子矩阵比较完后的max即为所求
if(max < tempMax){
max = tempMax;
}
}
}
cout << max << endl;
return 0;
}