Largest Rectangle in a Histogram(單調棧)

Largest Rectangle in a Histogram

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 33874   Accepted: 11045

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

   求:直方圖中的最大矩形 

   思路:暴力法的話就是遍歷所有矩形,求出每個矩形向左向右延伸的最大寬度,然後乘以高度求出最大值 O(n^2)

   單調棧:O(n)

  當新元素的高度大於棧頂元素,直接入棧

 否則,計算棧頂元素的最大擴展面積,取最大值,出棧



import java.util.Scanner;
import java.util.Stack;
class node{
	  long height;
	  int width;
}
public class Main {
	       static int n;
	       static Stack<node> st=new Stack<node>();
	       public static void main(String[] args) {
	           Scanner scan=new Scanner(System.in);
	           while(scan.hasNext()){
      	         n=scan.nextInt();
      	         if(n==0) break;
      	         long ans=0;
      	         for(int i=1;i<=n+1;i++){
      	        	     node a=new node();//每次new
      	    	         if(i<=n) a.height=scan.nextInt();
      	    	         else   a.height=0;
      	    	         a.width=i;
      	    	          while(!st.isEmpty() && st.peek().height>=a.height ){
      	    	        	     ans=Math.max(ans, st.peek().height*(i-st.peek().width));
      	    	        	     a.width=st.peek().width;
      	    	        	     st.pop();
      	    	          }
      	    	          st.push(a);
      	         }
      	        System.out.println(ans);
	           }
		}
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章