CCF201312-3 最大的矩形

之前想了很久都没有明白,看了一些博客,自己动手一步一步排之后终于知道怎么回事了。有了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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值