题目链接:POJ 2559
代码如下:
// STL stack版
#include <utility>
#include <cstdio>
#include <stack>
using namespace std;
#define fi first
#define se second
const int N = 111111;
typedef long long ll;
typedef pair<int, int> pii;
ll a[N]; // from 1 to n / [1, n]
struct monotone_stack
{
stack<pii> sk; // first = startpos, second = index of a[]
ll mx[N], m; // mx = max rectangle area through a[i] , m = max(mx[])
// 栈底元素下标为0,值为0
void clear() {
m = -(int)1e9;
while(!sk.empty()) sk.pop();
sk.push(pii(0, 0));
}
void push(int x) {
while(sk.size() > 1) {
pii t = sk.top();
if(a[t.se] > a[x]) {
mx[t.se] = (x - t.fi) * a[t.se];
if(m < mx[t.se]) m = mx[t.se];
sk.pop();
}
else break;
}
if(a[sk.top().se] == a[x]) sk.push(pii(sk.top().fi, x));
else sk.push(pii(sk.top().se + 1, x));
}
void solve(int x) { // x is the (end + 1) index of a[]
while(sk.size() > 1) {
pii t = sk.top();
mx[t.se] = (x - t.fi) * a[t.se];
if(m < mx[t.se]) m = mx[t.se];
sk.pop();
}
}
ll segm() { return m; }
} s;
int main()
{
// freopen("in", "r", stdin);
int n;
while(scanf("%d", &n), n) {
s.clear();
for(int i = 1; i <= n; i++) {
scanf("%I64d", a + i);
s.push(i);
}
s.solve(n + 1);
printf("%I64d\n", s.segm());
}
return 0;
}