• 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;
    }
    
  • 相关阅读:
    jfinal使用配置文件注意事情
    在项目中集成jetty server
    JFinal快速上手及注意事项
    表单处理的方案与注意事项(servlet)
    java四大会话技术
    servlet过滤器简化版
    python 生成器
    python 深复制和浅复制
    python 获取路径
    python selenium定位总结(转)
  • 原文地址:https://www.cnblogs.com/fusiwei/p/13924762.html
Copyright © 2020-2023  润新知