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
8 4000
首先要看到这句话:"Each test case describes a histogram and starts with an integer n, denoting the number of rectangles it is composed of."。。如果sample input 改成这样会好理解点:
7
2 1 4 5 1 3 3
4
1000 1000 1000 1000
0
因为可能是很大的数,,。所以要用C++的64位扩展:_int64.. 格式控制符也用用%I64d...注意里面是大写的"i".。
又要定义N个大数组:如果定义在main函数内的话,系统为数组分配的是栈空间,。嗯,栈空间是很小的,远远不够这道题的花销。所以定义成全局变量。这样系统就会在编译的时候在数据段开辟空间。
这道题只需找出每个点向左右延伸的最大范围,并计算出面积。再找出最大值即可;例:
输入的数据: 2 1 4 5 1 3 3
对应数组下标: 0 1 2 3 4 5 6
向左延伸的最大下标: 0 0 2 3 0 5 5
向右延伸的最大下标: 0 6 3 3 6 6 6
面积: 2 7 8 5 7 6 6 所以:最后结果是8
当然不能用直接搜索的办法,那样肯定会超时。考虑DP:如果h[i]>=h[i-1];则h[i-1]的左边界也大于等于h[i].。。
#include<stdio.h>
_int64 n[100005];
_int64 l[100005];
_int64 r[100005];
//6 2 5 2 5 5 2
int main()
{
_int64 i;
_int64 k;
_int64 c;
for(;;)
{
scanf("%I64d",&c);
for(i=0;i<c;i++)
scanf("%I64d",&n[i]);
if(c==0) //只输入一个数,且为0时结束
break;
k=i;
for( i=0;i<k;i++)
{
l[i]=i;
while( l[ l[i] ]>0 && n[ l[i]-1 ]>=n[i] )
l[ i ]=l[ l[i]-1 ];
}
for( i=k-1;i>=0;i--)
{
r[i]=i;
while( r[r[i]]<k-1 && n[r[i]+1]>=n[i] )
r[i]=r[r[i]+1];
}
// for(i=0;i<k;i++)
// printf("%I64d:%I64d ",l[i],r[i]);
// printf("\n");
_int64 temp;
temp=(r[0]-l[0]+1)*n[0];
for(i=0;i<k;i++)
{
// printf("%I64d",temp);
if(temp<(r[i]-l[i]+1)*n[i] )
temp=(r[i]-l[i]+1)*n[i];
// printf("%I64d",temp);
}
printf("%I64d\n",temp);
}
return 0;
}