上海交大OJ1002.二哥种花生
记录一下自己的OJ之路
今天开始刷学校的OJ,从最简单的开始,以后有时间就来刷一刷
题目
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
4 5
1 2 3 4 5
6 7 8 0 0
0 9 2 2 3
3 0 0 0 1
3 3
Sample Output
38
样例解释
左上角:38 = (1+2+3) + (6+7+8) + (0+9+2)
数据范围
对于30%的数据: 1≤L,W≤100;
对于100%的数据: 1≤L,W≤1000
全部区域大小满足:1≤a≤L,1≤b≤W
初步思路
1002啊,自然首先情不自禁暴力破解
/1002.二个种花生
/普通数组的形式/
// 测试结果:50分
// 可能是调用太慢了吧
// 十次测试,五次通过,四次超时,一次错误
#include <iostream>
using namespace std;
int shape[1001][1001];
int main()
{
int L, W;
cin >> W >> L;
for (int i = 0; i < W; ++i)
for (int j = 0; j < L; ++j)
cin >> shape[i][j];
int nl, nw, m = 0, temp = 0;
cin >> nl >> nw;
for (int i = 0; i < W - nw; ++i)
for (int j = 0; j < L - nl; ++j)
{
for (int k = 0; k < nw; ++k)
for (int t = 0; t < nl; ++t)
temp += shape[i + k][j + t];
if (temp > m)
m = temp;
temp = 0;
}
cout << m;
return 0;
}
不行,凉凉,试试动态的
///1002.二个种花生
///动态数组的形式/
// 测试结果:50分
// 可能是调用太慢了吧
// 十次测试,五次通过,四次超时,一次错误,和普通数组一样
#include <iostream>
using namespace std;
int main()
{
int L, W;
cin >> W >> L;
int **shape = new int *[W];
for (int i = 0; i < W; ++i)
shape[i] = new int[L];
for (int i = 0; i < W; ++i)
{
for (int j = 0; j < L; ++j)
cin >> shape[i][j];
}
int l, w, m = 0, temp = 0;
cin >> w >> l;
for (int i = 0; i < W - w; ++i)
{
for (int k = 0; k < L - l; ++k)
{
if (temp > m)
m = temp;
temp = 0;
for (int n = 0; n < w; ++n)
for (int j = 0; j < l; ++j)
temp += shape[i + n][k + j];
}
}
cout << m;
return 0;
}
换个思路
1000×1000的数组遍历起来复杂度至少是O(n2)吧,时间耗不起啊
用大家都用的前缀和解法试试,自己再写一遍方法和原理很简单如上图,这样右下角的元素就表示所在矩阵的累加,然后就是元素之间加减的问题了,代码如下:
// /1002.二个种花生
// /普通数组的前缀和形式/
//完美通过,get a new skill
#include <iostream>
using namespace std;
int shape[1001][1001];
int main()
{
int L, W;
cin >> W >> L;
for (int i = 1; i <= W; ++i) //从一开始,让上面和左面的元素都是0!
for (int j = 1; j <= L; ++j)
{
cin >> shape[i][j];
shape[i][j] += shape[i - 1][j] + shape[i][j - 1] - shape[i - 1][j - 1];//关键
}
int nl, nw, m = 0, temp = 0;
cin >> nw >> nl;
for (int i = nw; i <= W; ++i)
for (int j = nl; j <= L; ++j)
{//注意减去shape[i-nw][j-nl];
temp = shape[i][j] - shape[i - nw][j] - shape[i][j - nl] + shape[i-nw][j-nl];
if (temp > m)
m = temp;
temp = 0;
}
cout << m;
return 0;
}
测试成功,没想到OJ的道路一开始就这么充满挑战,大家加油啦!