http://poj.org/problem?id=2559
不是很难的题……大一的时候貌似就写过,但是思路忘了。这次是用单调栈写的。
题目大意:在一排的矩形中找出一个面积最大的能够覆盖连续矩形的大矩形,这个大矩形的高不超过被覆盖矩形的最矮的高。
(我还是不太懂记录刷过的题有什么用处。有很明显的帮助吗?能够帮你系统地归纳整理算法和心得?如果大牛们看到了请不吝赐教……)
对了,之前h数组是int,但是wa了,改成long long才对,因为tarea = h[i] * (r[i] - l[i] - 1)。此句中,右侧都是int类型,结果就算tarea是long long也没用。
/*
* rectangle.cpp
* Created on: 2014年12月18日
* Author: Pan Hong
*/
/*
* 方法:
* 单调栈
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring> //for memset
#include <algorithm>
#include <stack>
#define MAXN 100005
using namespace std;
long long int h[MAXN];//从1开始用
int l[MAXN], r[MAXN];
int main()
{
int n;
stack<int> pos;
while(cin >> n && n)
{
pos.push(0);
memset(l, 0, sizeof(l));
memset(r, 0, sizeof(r));
memset(h, 0, sizeof(h));
h[0] = -1;
for(int i = 1; i <= n; i++)
{
cin >> h[i];
if(h[i] > h[pos.top()])//当前元素高度大于栈顶
{
l[i] = pos.top();//记录左侧第一个小于h[i]高度的位置
pos.push(i);
}
else//小于等于栈顶
{
while(h[i] <= h[pos.top()])//直到栈顶小于h[i]
{
pos.pop();
}
l[i] = pos.top();
pos.push(i);
}
}//输入树高,顺便求l数组.l数组内容可能是0,此时表示左边无更小的值了。
while(!pos.empty())
{
pos.pop();
}//清空栈
h[n+1] = -1;
pos.push(n+1);
for(int i = n; i >= 1; i--)
{
if(h[i] > h[pos.top()])
{
r[i] = pos.top();
pos.push(i);
}
else
{
while(h[i] <= h[pos.top()])
{
pos.pop();
}//一直弹到栈顶小于当前高度
r[i] = pos.top();
pos.push(i);
}
}//计算r数组的内容
long long int area = 0;
long long int tarea;
for(int i = 1; i <= n; i++)
{
tarea = h[i] * (r[i] - l[i] - 1);
area = area > tarea ? area : tarea;
}
cout << area << endl;
}
}