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;
    }
    
  • 相关阅读:
    正则表达式分组()、不捕获(?:)和断言(?<=)详解
    正则匹配IP
    正则匹配中文
    SPL--Serializable
    JavaScript中原型和原型链
    JavaScript中变量和函数声明的提升
    运行gulp提示:Task function must be specified
    vue-router 去掉#
    学以致用 ---- vue子组件→父组件通信
    删除node_modules
  • 原文地址:https://www.cnblogs.com/fusiwei/p/13924762.html
Copyright © 2011-2022 走看看