题意:给你一堆紧挨着的高度不定,长度为1的矩形,让你求最大矩形面积.
分析:
用单调栈维护一个最长非递减序列,遇到不满足的情况,直接出栈并计算面积(这个面积以pop的高度为高度,长取最长).
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
using namespace std;
typedef long long LL;
typedef pair<LL, LL> pii;
stack<pii> s;
int main() {
LL n, k;
while(scanf("%lld", &n) && n) {
while(!s.empty()) s.pop();
scanf("%lld", &k);
s.push(pii(k, 1LL));
LL ans = 0, len;
for(int i = 0; i < n - 1; ++i) {
scanf("%lld", &k);
if(k >= s.top().first) {
s.push(pii(k, 1LL));
continue;
}
len = 0;
while(s.top().first > k) {
len += s.top().second;//注意长度的更新
if(ans < s.top().first * len) {
ans = s.top().first * len;
}
s.pop();
if(s.empty()) break;
}
s.push(pii(k, len + 1LL));
}
len = 0;
while(!s.empty()) {
len += s.top().second;;
if(ans < s.top().first * len) {
ans = s.top().first * len;
}
s.pop();
}
printf("%lld\n", ans);
}
return 0;
}