poj2082单调栈

本来实在做后缀数组的题目的,不巧,碰到了pku3415这题,需要用到单调栈来维护,但是之前又没有学习过单调栈这方面的知识,于是水了几题.......

题意:给你一些连续的小矩形,高宽不定,求最大的矩形面积........

思路:直接用单调栈,当有一个矩形的高小于等于栈顶元素的高时,出栈,并维护这个即将入栈的元素的向前延伸的宽度范围,维护出栈后的栈顶元素向后延伸的宽度范围.......

#include<iostream>
#include<stack>
#include<stdio.h>
using namespace std;
struct node
{
	__int64 h,pre,next,w;
};
int main()
{
	int n;
	while(scanf("%d",&n)>0)
	{
		if(n==-1)
		break;
		stack<node>Q;
		node tmp;
		__int64 ans=0,sum=0,num;
		scanf("%I64d%I64d",&tmp.w,&tmp.h);
		tmp.pre=tmp.w;
		tmp.next=tmp.w;
		Q.push(tmp);
		for(int i=1;i<n;i++)
		{
			scanf("%I64d%I64d",&tmp.w,&tmp.h);
			tmp.pre=tmp.next=tmp.w;
			while(!Q.empty()&&tmp.h<=Q.top().h)
			{
				node tmp1=Q.top();
				Q.pop();
				ans=tmp1.h*(tmp1.pre+tmp1.next-tmp1.w);
				if(!Q.empty())
				Q.top().next+=tmp1.next;
				tmp.pre+=tmp1.pre;
				if(ans>sum)
				sum=ans;
			}
			Q.push(tmp);
		}
		while(!Q.empty())
		{
			node tmp1=Q.top();
			Q.pop();
			if(!Q.empty())
			Q.top().next+=tmp1.next;
			ans=tmp1.h*(tmp1.pre+tmp1.next-tmp1.w);
			if(ans>sum)
			sum=ans;
		}
		printf("%I64d\n",sum);
	}
	return 0;
} 

 

posted @ 2013-06-23 20:17  紫忆  阅读(1170)  评论(0编辑  收藏  举报