标签:
http://acm.hdu.edu.cn/showproblem.php?pid=1081
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10874 Accepted Submission(s): 5204
Sample Input
4
0 -2 -7 0 9 2 -6 2
-4 1 -4 1 -1
8 0 -2
Sample Output
15
动态规划问题
可以将二维数组压缩成一维数组,求压缩后的数字最大子段和,即二维数组的最大子矩阵和。
将二维数组压缩:将第1行到第n行的每一列都加起来,即a[i][j]表示第j列前1-i行数的和,再求第i行最大子段和就可以了
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cstring> 5 using namespace std; 6 int main(){ 7 int n, a[110][110], i, j, k; 8 while(cin>>n){ 9 memset(a, 0, sizeof(a)); 10 for(i=1; i<=n; i++){ 11 for(j=1; j<=n; j++){ 12 cin>>a[i][j]; 13 a[i][j] += a[i-1][j];//a[i][j]表示第j列前i行数的和 14 } 15 } 16 int mmax = -1000000, sum; 17 for(i=1; i<=n; i++){ 18 for(k=1; k<=i; k++){ 19 sum = 0; 20 for(j=1; j<=n; j++){ 21 sum += (a[i][j]-a[k-1][j]); 22 if(sum > mmax) 23 mmax = sum; 24 if(sum < 0) 25 sum = 0; 26 } 27 } 28 } 29 cout<<mmax<<endl; 30 } 31 return 0; 32 }
标签:
原文地址:http://www.cnblogs.com/wudi-accept/p/5334247.html