题目:http://poj.org/problem?id=2559
题意:给出n个长方形并排排列,每个宽为1,高为hi,你在这些长方形覆盖的区域地方涂一个长方形出来,这个长方形最大面积是多少。
思路:
所图区域,如果高为hi,那么
最左边涂到的长方形 l 满足,h(l-1) < hi (l值尽量大)
最右边涂到的长方形 r 满足,h(r+1) < hi (r值尽量小)
l <= i <= r
预处理出 L[ i ] 和 R[ i ],然后枚举 (R[ i ] - L[ i ] + 1) * hi 得到答案
用盏得到L[ i ] :当栈顶元素 hj >= hi 则取出栈顶元素,直到 hj < hi,L[i] = j + 1,再把 i 压入栈。如果栈为空,则 L[i] = 0。
同理可得R[i]。
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <stdlib.h>
#define INF 0x7fffffff
#define MOD 1000000007
using namespace std;
typedef long long ll;
const int MAXN = 100005;
int a[MAXN], L[MAXN], R[MAXN];
struct P
{
int th, h;
}cur, sta[MAXN];
int main()
{
#ifdef LOCAL
freopen("data.in", "r", stdin);
#endif
int n;
while(scanf("%d", &n) != EOF && n)
{
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
int t = 0;
cur.th = 0; cur.h = a[0];
L[0] = 0;
sta[0] = cur;
//printf("%d %d\n", sta[0].th, sta[0].h);
for(int i = 1; i < n; i++)
{
cur.th = i; cur.h = a[i];
while(sta[t].h >= cur.h && t >= 0)
t--;
if(t == -1)
L[i] = 0;
else
L[i] = sta[t].th + 1;
sta[++t] = cur;
}
t = 0;
cur.th = n - 1; cur.h = a[n - 1];
sta[0] = cur;
R[n - 1] = n - 1;
for(int i = n - 2; i >= 0; i--)
{
cur.th = i; cur.h = a[i];
while(sta[t].h >= cur.h && t >= 0)
t--;
if(t == -1)
R[i] = n - 1;
else
R[i] = sta[t].th - 1;
sta[++t] = cur;
}
ll ans = 0;
for(int i = 0; i < n; i++)
{
ll temp = (ll)a[i] * (R[i] - L[i] + 1);
ans = max(temp, ans);
}
printf("%lld\n", ans);
}
return 0;
}