首页 > 其他 > 详细

S - 单调栈

时间:2017-03-21 22:53:45      阅读:248      评论:0      收藏:0      [点我收藏+]
A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3, measured in units where 1 is the width of the rectangles: 
技术分享 
Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. The figure on the right shows the largest aligned rectangle for the depicted histogram.

InputThe input contains several test cases. Each test case describes a histogram and starts with an integer n, denoting the number of rectangles it is composed of. You may assume that 1 <= n <= 100000. Then follow n integers h1, ..., hn, where 0 <= hi <= 1000000000. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is 1. A zero follows the input for the last test case.OutputFor each test case output on a single line the area of the largest rectangle in the specified histogram. Remember that this rectangle must be aligned at the common base line.Sample Input

7 2 1 4 5 1 3 3
4 1000 1000 1000 1000
0

Sample Output

8
4000

分析:找出左边比它大的和右边比他大的
#include<stdio.h>
long long m[100010];
long long add[100010],l[100010],r[100010];

int main()
{
	int n;
	scanf("%d",&n);
	while(n!=0)
	{
		long long s=0,flag;
		for(int i=1;i<=n;i++)
			scanf("%I64d",&m[i]);
		l[1]=1;
		r[n]=n;
		for(int i=2;i<=n;i++)
		{
			int tt=i;
			while(tt>1&&m[i]<=m[tt-1])tt=l[tt-1];
			l[i]=tt;
		}
		for(int i=n-1;i>=1;i--)
		{
			int tt=i;
			while(tt<n&&m[i]<=m[tt+1])tt=r[tt+1];
			r[i]=tt;
		}
		for(int i=1;i<=n;i++)
		{
			flag=(r[i]-l[i]+1)*m[i];
			if(s<flag)
				s=flag;	
		}
		printf("%I64d\n",s);
		scanf("%d",&n);	
	}
	return 0;	
}

  

S - 单调栈

原文:http://www.cnblogs.com/xzxj/p/6597066.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!