题意:给定从左到右多个矩形,已知这此矩形的宽度都为1,长度不完全相等。这些矩形相连排成一排,求在这些矩形包括的范围内能得到的面积最大的矩形,打印出该面积。所求矩形可以横跨多个矩形,但不能超出原有矩形所确定的范围。
单调栈:由提议得知,我们采用单调栈,顾名思义就是在入栈时遵循单调原则,可以求出一个元素向左(或向右)所能扩展到的最大长度,并不是说在这一段区间内是单调的,而是保证在该区间内该元素一定是最大或最小。
源码:
#include <cstdio>
#include <iostream>
#define ll long long
using namespace std;
struct my
{
ll h;
int id;
} wo[100005];
ll d[100005];
int main()
{
int n;
while (cin>>n, n) {
int i, j;
for (i = 1; i <= n; ++i) {
scanf("%lld", &d[i]);
}
d[n + 1 ] = 0;
wo[1].h = d[1];
wo[1].id = 1;
int top = 1;
ll ans = 0;
for (i = 2; i <= n + 1; ++i) {
if (d[i] >= wo[top].h) {
++top;
wo[top].h = d[i];
wo[top].id = i;
} else {
while (top >= 0 && wo[top].h > d[i]) {
ll tmp = (i - 1 - wo[top].id + 1) * wo[top].h;
if (tmp > ans)
ans = tmp;
--top;
}
++top;
wo[top].h = d[i];
}
}
printf("%lld\n", ans);
}
return 0;
}