• POJ 2559 Largest Rectangle in a Histogram


    POJ 2559 Largest Rectangle in a Histogram

    POJ传送门

    洛谷传送门

    Description

    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:
    img
    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.

    Input

    The 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.

    Output

    For 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<cstdio>
    #include<algorithm>
    #define int long long
    using namespace std;
    const int maxn=1e5+5;
    int n,ans;
    int a[maxn];
    int s[maxn],top;
    int l[maxn],r[maxn];
    signed main()
    {
    	while(scanf("%lld",&n)&&n)
    	{
    	ans=0;
    	for(int i=1;i<=n;i++)
    		scanf("%lld",&a[i]);
    	a[0]=a[n+1]=-1;
    	while(top)
    		top--;
    	for(int i=1;i<=n+1;i++)
    	{
    		while(top && a[i]<a[s[top]])
    		{
    			r[s[top]]=i;
    			top--;
    		}
    		s[++top]=i;
    	}
    	while(top)
    		top--;
    	for(int i=n;i>=0;i--)
    	{
    		while(top && a[i]<a[s[top]])
    		{
    			l[s[top]]=i;
    			top--;
    		}
    		s[++top]=i;
    	}
    	for(int i=1;i<=n;i++)
    	{
    		int len=r[i]-1-l[i];
    		int tmp=a[i]*len;
    		ans=max(ans,tmp);
    	}
    	printf("%lld
    ",ans);
    	}
    	return 0;
    }
    
  • 相关阅读:
    如何心无旁鹜的编程
    [转]虚拟现实和现实增强技术带来的威胁
    Mac上好用软件集锦
    无论如何都要来报到
    Unity3D脚本语言UnityScript初探
    X3DOM新增剪裁平面节点ClipPlane支持
    用Perl编写Apache模块续二
    如何浪费自己青春
    macbook 我们需要买吗
    看了一本Unity3D的教程
  • 原文地址:https://www.cnblogs.com/fusiwei/p/13924762.html
Copyright © 2020-2023  润新知