hdu 1506 Largest Rectangle in a Histogram 矩阵系列(一)

Largest Rectangle in a Histogram

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7496    Accepted Submission(s): 2106


Problem 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:
hdu 1506 Largest Rectangle in a Histogram 矩阵系列(一)_第1张图片
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

题目意思:

给你n,然后告诉你这n段的高度,这样就组成了一个直方图

为你直方图中最大的矩形的面积是多少

解题思路:
对于每个高度h[i],迭代找出它的最左边以及最右边
对于h[i]而言,如果<= 左边 的h[i-1],则他的最左边一定是i-1的最左边,然后一直迭代下去
ps:迭代的过程是很快的
#include <iostream>
#include <cstdio>
#define maxn 100005
using namespace std;

int n,m;
__int64 h[maxn],le[maxn],ri[maxn];
__int64 ans;

void left()              // 向左迭代
{ 
    int i,j;
    for(i=1;i<=n;i++)
    {
        le[i]=1;
        while(h[i-le[i]]>=h[i])
        {
            le[i]+=le[i-le[i]];
        }
    }
}
void right()             // 向右迭代
{
    int i,j;
    for(i=n;i>=1;i--)
    {
        ri[i]=1;
        while(h[i+ri[i]]>=h[i])
        {
            ri[i]+=ri[i+ri[i]];
        }
    }
}
void solve()                  
{
    int i;
    ans=-1;
    for(i=1;i<=n;i++)     // 更新ans
    {
        if((le[i]+ri[i]-1)*h[i]>ans) ans=(le[i]+ri[i]-1)*h[i];
    }
}
int main()
{
    int i,j;
    while(scanf("%d",&n),n)
    {
        for(i=1;i<=n;i++)
        {
            scanf("%I64d",&h[i]);
        }
        h[0]=h[n+1]=-1;     // 加边界条件
        left();
        right();
        solve();
        printf("%I64d\n",ans);
    }
    return 0;
}


你可能感兴趣的:(hdu 1506 Largest Rectangle in a Histogram 矩阵系列(一))