poj 2559 Largest Rectangle in a Histogram (单调栈)

poj 2559

题意:给定从左到右多个矩形,已知这此矩形的宽度都为1,长度不完全相等。这些矩形相连排成一排,求在这些矩形包括的范围内能得到的面积最大的矩形,求该面积。所求矩形可以横跨多个矩形,但不能超出原有矩形所确定的范围。

思路:单调栈。。。好久没写了,感觉之前一直也没有完全掌握单调栈的技巧。这回一定要掌握。

对于这道题,我们对于每个位置i,用两个单调栈维护出最左边和最右边最远能到达的位置。然后扫一遍更新最大值。

单调栈部分我用了stl 的stack

细节见注释

/* ***********************************************
Author :111qqz
Created Time :2016年08月03日 星期三 04时27分31秒
File Name :code/poj/2559.cpp
************************************************ */
 1#include <cstdio>
 2#include <cstring>
 3#include <iostream>
 4#include <algorithm>
 5#include <vector>
 6#include <queue>
 7#include <set>
 8#include <map>
 9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#include <stack>
14#define fst first
15#define sec second
16#define lson l,m,rt<<1
17#define rson m+1,r,rt<<1|1
18#define ms(a,x) memset(a,x,sizeof(a))
19typedef long long LL;
20#define pi pair < int ,int >
21#define MP make_pair
 1using namespace std;
 2const double eps = 1E-8;
 3const int dx4[4]={1,0,0,-1};
 4const int dy4[4]={0,-1,1,0};
 5const int inf = 0x3f3f3f3f;
 6const int N=1E5+7;
 7int l[N],r[N];
 8stack<int>stk;
 9int a[N];
10int n;
11int main()
12{
13	#ifndef  ONLINE_JUDGE 
14	freopen("code/in.txt","r",stdin);
15  #endif
16	while(scanf("%d",&n)!=EOF)
17	{
18	    if (n==0) break;
19	    for ( int i = 1 ; i <= n ; i++) scanf("%d",&a[i]);
20	    a[0]=-1;
21	    a[n+1]=-1;
22	    while (!stk.empty()) stk.pop();
23	    stk.push(0);
24	    int x;
25	    for ( int i = 1 ; i <= n ; i++)
26	    {
27		for ( x = stk.top() ; a[x]>=a[i] ; x = stk.top()) stk.pop(); //找到栈中第一个(离a[i]最近的)小于a[i]的位置
28		l[i] = x+1;//第一个小于a[i]的位置的右边就是i位置往左最远能达到的不减的位置。
29		stk.push(i); //栈已经处理成单调了,此时可以入栈。
30	    }
	    //再反向做一次。
	    while (!stk.empty()) stk.pop();
1	    stk.push(n+1);
2	    for ( int i = n ; i >=1 ; i--)
3	    {
4		for ( x=  stk.top() ; a[x]>=a[i] ; x = stk.top()) stk.pop();
5		r[i] = x-1;// 第一个小于a[i]的位置的左边就是i位置往右最远能达到的不减的位置。
6		stk.push(i);
7	    }
1	    LL ans = 0LL;
2//	    for ( int i = 1; i <= n ; i++) printf("i:%d l[i]:%d r[i]:%d\n",i,l[i],r[i]);
3	    for ( int i = 1 ; i <= n ; i++)
4		ans = max(ans,1LL*(r[i]-l[i]+1)*a[i]);
	    printf("%lld\n",ans);

	}
1  #ifndef ONLINE_JUDGE  
2  fclose(stdin);
3  #endif
4    return 0;
5}