上海交大OJ 1002.二哥种花生@TOC
问题
Description
二哥在自己的后花园里种了一些花生,也快到了收获的时候了。这片花生地是一个长度为L、宽度为W的矩形,每个单位面积上花生产量都是独立的。他想知道,对于某个指定的区域大小,在这么大的矩形区域内,花生的产量最大会是多少。
Input Format
第1行有2个整数,长度L和宽度W。
第2行至第L+1行,每行有W个整数,分别表示对应的单位面积上的花生产量A( 0≤A<10 )。第L+2行有2个整数,分别是指定的区域大小的长度a和宽度b。
Output Format
输出一个整数m,表示在指定大小的区域内,花生最大产量为m。
Sample Input
Sample Output
算法分析
由sample 以为只要输出左上角的那一块的花生数量的和即可,提交后发现答案错误才明白应该是输出所有可能的地块中花生数量和最多的。
遍历
如果要遍历计算,可容易得知需要遍历四次。那么复杂度会非常高(实际上由于时间超出无法通过测试)
#include<iostream>
using namespace std;
int main()
{
int L, W;
cin >> L >> W;
int **A = new int*[L];
for (int i = 0; i < L; ++i) A[i] = new int[W];
//输入
for (int i = 0; i < L; ++i){
for (int j = 0; j < W; ++j)
cin >> A[i][j];
}
int a, b,result,temp;
cin >> a >> b;
//遍历计算,四重循环
for (int m =0; m < W-b+1; ++m){
for (int n = 0; n< L-a+1; ++n){
temp = 0;
for (int i = n; i < n+a; ++i){
for (int j = m; j < m+b; ++j){
temp += A[i][j];
}
}
if (result <= temp) result = temp;