HDU 1506 Largest Rectangle in a Histogram(DP)

题目地址:点击打开链接

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:

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


4000

如果暴力搜索,肯定会超时,不妨DP找出从第i条边向两侧延伸,只要下一条边大于这条边的长度,就储存在数组中,最后遍历一遍,若两个最长边的距离乘上第i条边的距离,也就是矩形的高大于最大值,则记录为最大值。需要两个数组分别储存左边的值跟右边的值。 
还要注意变量形式,要用到long long 或者__int64 不然会WA。

详情看代码。

#include
#include
#include

using namespace std;

__int64 n,a[100005],l[100005],r[100005];  //left跟right分别储存a[i]左右的连续的比a[i]长的边长 

void DP()
{
	int i,j,t;
	__int64 max;
	
	for(i=2;i<=n;i++)  //从第二个开始遍历 
	{
		t=i;          //t用来接收i 
		while(t>1&&a[i]<=a[t-1])   // t保持在第二个以上 ,且满足下一条边大于这条边 
		{
			t=l[t-1];             //边左移 
		}  
		l[i]=t;                   //记录 
	}
	
	for(i=n-1;i>0;i--)  //从倒数第二个开始遍历 
	{
		t=i;
		while(t>n)&&n)
	{
		for(i=1;i<=n;i++)
		{
			cin>>a[i];
		}
		
		l[1]=1;    //从第二个数开始判断,第一个设为1 
		r[n]=n;    //从倒数第二个开始判断,倒数第一个设为n 
		
		DP();
	}
	return 0;
}


你可能感兴趣的:(******DP******,******HDU******)