zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    L110 promise
    2018.7.7 MBA -从专业到管理(1)—— 技术人才与的管理人才比较
    2018.7.9 AVR-BAT program
    2018.7.6 TX射频调试-PP
    红外伪装(利用石墨烯通电)
    2018.7.2 AK22 不良品分析
    2018.6.25会议跟进
    2018.6.24异常跟进
    PyQt(Python+Qt)学习随笔:Model/View中的枚举类 Qt.MatchFlag的取值及含义
    PyQt(Python+Qt)学习随笔:基于项的项部件(Item Widgets(Item-Based))概述
  • 原文地址:https://www.cnblogs.com/fusiwei/p/13924762.html
Copyright © 2011-2022 走看看