HDOJ 1506 : Largest Rectangle in a Histogram DP求解

    题目URL:http://acm.hdu.edu.cn/showproblem.php?pid=1506

 这是一道动态规划求解题目,如果暴力枚举起点和终点的话,以这道题目的数据量,必然超时。

 动态规划求解的两个重要函数,left[i]:表示从left[i]到i的所有的立方柱的高度都大于或等于第i个立方柱的高度。很显然,当前i-1个的leff[i]求解出来之后,left[i]的求解便很简单了,不断的往前跳跃的找就行了。

   HDOJ上不认long long类型,得用_int64这种64位的长整型。

   我的AC代码:

#include <iostream>
#include <stdio.h>
using namespace std;

const int Max = 100000 + 10;
_int64 le[Max], ri[Max], h[Max];

int main()
{
	int n;
	while(scanf("%d", &n) && n)
	{
		h[0] = h[n+1] = -1;
		for(int i(1); i<=n; ++i) scanf("%I64d", h+i);

		for(int i=1; i<=n; ++i)
		{
			le[i] = i;
			while(h[i] <= h[le[i] - 1]) le[i] = le[le[i] - 1];
		}

		for(int i=n; i>=1; --i)
		{
			ri[i] = i;
			while(h[i] <= h[ri[i] + 1]) ri[i] = ri[ri[i] + 1];
		}

		_int64 max = 0;
		for(int i=1; i<=n; ++i)
		{
			_int64 temp = (ri[i] - le[i] + 1) * h[i];
			max = max > temp ? max : temp;
		}
		printf("%I64d\n", max);
	}
	system("pause");
	return 0;
}




    题目如下:

Largest Rectangle in a Histogram

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


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:
HDOJ 1506 : Largest Rectangle in a Histogram DP求解_第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
 

Source
University of Ulm Local Contest 2003
 

Recommend
LL
 





你可能感兴趣的:(System)