Largest Rectangle in a Histogram
Time Limit: 2 Sec Memory Limit: 128 MB
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.

传送门:POJ2559

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

1
2
3
7 2 1 4 5 1 3 3
4 1000 1000 1000 1000
0

Sample Output

1
2
8
4000

题解

想了一天突然领悟,单调栈不过尔尔,就是求最近的满足跳出条件的下标 怎么说那,对这道题,每个以shu[i]为高的长方形,它能往左右扩展,扩展到比自己小的高度结束 要求的就是左边和右边的那个边界下标 而这能用单调栈从左往右扫一遍和从右往左扫一遍解决
## AC code:(不包含输入类)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.io.*;  
import java.util.*;
public class Main {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
while(sc.hasNext()){
int n=sc.nextInt();
if(n==0)break;
long []shu=new long[n];
for(int i=0;i<n;i++){
shu[i]=sc.nextLong();
}
int[]right=new int[n];
int[]left=new int[n];
Stack<Integer>stack=new Stack<Integer>();
long max=0;
for(int i=0;i<n;i++){
if(stack.isEmpty()){
stack.add(i);
}else{
while(!stack.isEmpty()){
int temp=stack.peek();
if(shu[i]<shu[temp]){
right[temp]=i;
stack.pop();
}
else
break;
}
stack.add(i);
}
}
while(!stack.isEmpty()){
int temp=stack.pop();
right[temp]=n;
}
for(int i=n-1;i>=0;i--){
if(stack.isEmpty()){
stack.add(i);
}else{
while(!stack.isEmpty()){
int temp=stack.peek();
if(shu[i]<shu[temp]){
left[temp]=i;
stack.pop();
}
else
break;
}
stack.add(i);
}
}
while(!stack.isEmpty()){
int temp=stack.pop();
left[temp]=-1;
}
for(int i=0;i<n;i++){
max=Math.max(max, shu[i]*(right[i]-1-left[i]));
}
pw.println(max);
pw.flush();
}
}
}