POJ 2559 单调栈

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<queue>
#include<map>
#include<set>
using namespace std;

#define mxn 102000
#define inf 0x3f3f3f3f
#define eps 1e-8
#define LL long long 
#define ull unsigned long long
#define MP make_pair

struct node {
	LL h;		//节点高度
	int pos; // 开始位置
	node() {}
	node ( LL _h, int _pos ) {
		h = _h;
		pos = _pos;
	}
}a[mxn];
node stk[mxn];
int main() {
	int n;
	while( scanf( "%d", &n ) && n ) {
		for( int i = 1; i <= n; ++i ) {
			scanf( "%lld", &a[i].h );
		}
		int tail = 0;
		stk[0] = node( 0, 0 );  //防止出现栈为空的情况
		LL ans = 0;
		for( int i = 1; i <= n + 1; ++i ) {
			LL height = 0;
			if( i != n + 1 )   //i等于n+1弹出栈里所有节点
				height = a[i].h;
			node t( 0, i );
			while( stk[tail].h > height ) {
				t = stk[tail--];
				LL area = ( i - t.pos ) * t.h;
				ans = max( ans, area );
			}
			if( i == n + 1 )
				break;
			stk[++tail] = node( a[i].h, t.pos );
		}
		printf( "%lld\n", ans );
	}
	return 0;
}

你可能感兴趣的:(POJ 2559 单调栈)