Ural-1146Maximum Sum-最大子矩阵
2016-02-20 08:48
309 查看
Time limit: 0.5 second | Memory limit: 64 MB |
---|
As an example, the maximal sub-rectangle of the array:
0 | −2 | −7 | 0 |
---|---|---|---|
9 | 2 | −6 | 2 |
−4 | 1 | −4 | 1 |
−1 | 8 | 0 | −2 |
Input
The input consists of an N × N array of integers. The input begins with a single positive integer N on a line by itself indicating the size of the square two dimensional array. This is followed by N 2 integers separated by white-space (newlines and spaces). These N 2 integers make up the array in row-major order (i.e., all numbers on the first row, left-to-right, then all numbers on the second row, left-to-right, etc.). N may be as large as 100. The numbers in the array will be in the range [−127, 127].
Output
The output is the sum of the maximal sub-rectangle.
Sample
input | output |
---|---|
4 | 15 |
0 -2 -7 0 | |
9 2 -6 2 | |
-4 1 -4 1 | |
-1 8 0 -2 |
最大子矩阵和:以前做过一维的最大连续和,现在换成二维,而思路还是类似,不过要提前将二维的转化为一维,处理起来就是很方便,求出每一行的前缀和,然后枚举列,即可求出最大子矩阵和。
#include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <queue> #include <stack> #include <vector> #include <iostream> #include <algorithm> using namespace std; int n; int a[110][110]; int ans ; int main() { while(~scanf("%d",&n)) { memset(a,0,sizeof(a)); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { scanf("%d",&a[i][j]);//前缀和 a[i][j]+=a[i][j-1]; } } ans = -10000000; for(int i=1;i<=n;i++) { for(int j=i;j<=n;j++)//枚举列每一次求第i列到第j列之间的最大和 { int Max = -10000000; int sum = 0; for(int k=1;k<=n;k++) { sum+=(a[k][j]-a[k][i-1]); Max = max(Max,sum); if(sum<0) { sum = 0; } } ans = max(ans,Max); } } printf("%d\n",ans); } return 0; }
相关文章推荐
- C/C++ 函数所在的头文件(二)
- python输出excel能够识别的utf-8格式csv文件
- Struts2--ModelDriven接收参数
- juce教程001
- Struts2--DomainModel接收参数---使用广泛!!!
- 计算机图形学中的经常使用模型
- Android 内存泄露
- Android线程二、异步加载-新闻列表
- javaji基础x2
- Seoer,牵起用户与搜索引擎双手的魔术师
- 待完善
- word2vec浅析
- android高仿微信拍照、多选、预览、删除(去除相片)相冊功能
- Struts2--Action属性接收参数
- Win10输入法无法选择,右下角出现叉号,提示IME被禁用
- string和stringbuffer stringbuilder的快速理解。
- 微信背后的产品观---张小龙内部8小时演讲
- 无线电空间传输损耗衰减计算(转帖)
- JAVA的包装类
- C++之路进阶——队列优化dp(玩具装箱)