之前想了很久都没有明白,看了一些博客,自己动手一步一步排之后终于知道怎么回事了。有了2种方法,其中第二种方法用了栈,但是怎么试都是20分,不知道怎么回事。
解法一:各矩形高度存在height[n]数组中,从i=0开始遍历,可能的矩形长lenght=j-i+1,宽width=min(height[i]...height[j-1]),然后最大面积maxsquare=lenght*width,每次i++时都比较前一个maxsquare和现在的。这样就能得到最大面积了。
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int height[1000];
int maxsquare = 0;
for (size_t i = 0; i < n; ++i)
{
cin >> height[i];
}
for (size_t i = 0; i < n; ++i)
{
for (size_t j = i + 1; j < n; ++j)
{
int lenght = j - i + 1;
int width = height[i];
for (size_t t = i+1; t <= j; ++t)
{
if (width > height[t])
width = height[t];
}
if(maxsquare<lenght*width)
maxsquare = lenght*width;
}
}
cout << maxsquare << endl;
return 0;
}
解法二:用堆栈。只有20分。
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
class solution
{
public:
int Largevalue(vector<int> &height)
{
int result = 0;
stack<int> stk;
int ret = 0;
for (int i = 0; i < height.size(); ++i)
{
int count = 0;
if (stk.empty() || stk.top() <= height[i])
{
stk.push(height[i]);
}
else
{
while (!stk.empty()&&stk.top()>height[i])
{
ret = stk.top()*(++count);
stk.pop();
}
if (ret > result)
result = ret;
while (count--)
stk.push(height[i]);
stk.push(height[i]);
}
}
int count = 1;
while (!stk.empty())
{
int temp;
temp = stk.top()*(count++);
stk.pop();
if (temp > result)
result = temp;
}
return result;
}
};
int main()
{
vector<int> height(1000);
solution a;
int n;
int p;
cin >> n;
for (size_t i = 0; i < n; ++i)
cin>>height[i];
cout <<a.Largevalue(height) << endl;
return 0;
}