1. 程式人生 > >Largest Rectangle in a Histogram(找面積最大的連續塊)

Largest Rectangle in a Histogram(找面積最大的連續塊)

Problem DescriptionA 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.
InputThe 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.
OutputFor 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 Input7 2 1 4 5 1 3 3 4 1000 1000 1000 1000 0
Sample Output8 4000

題目大意:給一個直方圖,然後找到能夠構成一個矩形的面積最大的連續的方塊,兩張圖片已經給出來了什麼是矩形面積的最大的聯通塊。

對於每個柱子,找到能夠到達的左邊最遠的地方和右邊最遠的地方,然後找出最大的面積就行了

ac:

#include<stdio.h>  
#include<string.h>  
#include<math.h>  
  
//#include<map>   
#include<deque>  
#include<queue>  
#include<stack>  
#include<string>  
#include<iostream>  
#include<algorithm>  
using namespace std;  
  
#define ll long long  
#define da    0x3f3f3f3f  
#define xiao -0x3f3f3f3f  
#define clean(a,b) memset(a,b,sizeof(a))// 雷打不動的標頭檔案  

ll Left[100100],Right[100100];
ll shuzu[100100];

int main()
{
	int n;
	while(cin>>n)
	{
		clean(Left,0);
		clean(Right,0);
		clean(shuzu,0);
		if(n==0)
			break;
		int i,j;
		for(i=1;i<=n;++i)
			scanf("%lld",&shuzu[i]);
		//找左邊的邊界 
		Left[1]=1;//最左邊是第一塊 
		for(i=2;i<=n;++i)//從第二個開始 
		{
			j=i; //向左查詢,如果該值>=當前值,就記錄位置並且繼續 
			while(j>1&&shuzu[j-1]>=shuzu[i])
				j=Left[j-1];//這裡Left中儲存的是 第幾塊 
			Left[i]=j;//最後找到的是能到達的 最左邊的距離 
		}
		//同理 右邊的邊界 
		Right[n]=n;//最右邊是第n塊 
		for(i=n-1;i>=1;--i)//從n-1開始 
		{
			j=i;//向右查詢,如果該值>=當前值,繼續 
			while(j<n&&shuzu[j+1]>=shuzu[i])
				j=Right[j+1];//right中是最右邊能到達的地方 
			Right[i]=j;//最後找到最右邊的距離 
		}
		ll maxx=0;
		for(i=1;i<=n;++i)//遍歷;找 所有面積並找最大的 
			maxx=maxx>(Right[i]-Left[i]+1)*shuzu[i]?maxx:(Right[i]-Left[i]+1)*shuzu[i];
		cout<<maxx<<endl;//輸出maxx 
	}
}