ZOJ 1074 To the Max

原题链接

题目大意:这是一道好题。在《算法导论》这本书里面,有一节是介绍如何求最大子序列的。这道题有点类似,区别是从数组变成了矩阵,求最大子矩阵。

解法:完全没有算法功底的人当然不知道最大子序列这么经典的东西。所以先请教Google。我是参考了这篇文章的,tengpi.blog.163.com/blog/static/22788264200772561412895/。大意就是另开辟一个同样大小的矩阵,每个元素存放自左侧第一列到该元素的和。然后在纵向上用最大子序列的类似方法计算。

参考代码:

/* tengpi.blog.163.com/blog/static/22788264200772561412895/   */

#include<iostream>

using namespace std;

int main(){
	int N,i,j,k,btemp,max=-12700;
	int A[100][101],B[100][101];
	while(cin>>N){
		for(i=0;i<N;i++){
				B[i][0]=0;
			for(j=1;j<=N;j++){
				cin>>A[i][j];
			}
		}
		for(i=0;i<N;i++){
			btemp=0;
			for(j=1;j<=N;j++){
				btemp+=A[i][j];
				B[i][j]=btemp;
			}
		}
		for(i=0;i<N;i++){
			for(j=i+1;j<=N;j++){
				btemp=0;
				for(k=0;k<N;k++){
					btemp+=B[k][j]-B[k][i];
					if(btemp>max)max=btemp;
					if(btemp<0)btemp=0;
				}
			}
		}
		cout<<max<<endl;
	}

	return 0;
}
原文地址:https://www.cnblogs.com/naive/p/3568760.html