Largest rectangle (CCF)

Problem Description
  Put on the horizontal axis n adjacent rectangles, the width of each rectangle is 1, and the first i (1 ≤ i ≤ n) is rectangular height H I . This constitutes a rectangle the n histograms. For example, the height of the figure are on six rectangular 3, 1, 6, 5, 2, 3.



  Find the histogram can be placed in a given area of the largest rectangle in which the side to be parallel to the axis. For the example given above, the maximum rectangular as shown shaded in FIG., The area of 10.
Input Format
  The first row contains an integer n, i.e. the number of rectangles (1 ≤ n ≤ 1000).
  The second line contains n integers H . 1 , H 2 , ..., H n , between adjacent numbers separated by a space. (H. 1 ≤ I  ≤ 10000). H i is the i-th height of the rectangle.
Output Format
  An output line, comprising an integer, i.e. to the largest histogram within a given rectangle.
Sample input
6
3 1 6 5 2 3
Sample Output
10
 
Ideas: monotonous stack maintenance

[ Draw ] we set up a stack, to hold a number of rectangles, these rectangles height is monotonically increasing. We left to right scan of each rectangle: If the rectangle is higher than the current top of the stack rectangular, directly into the stack.

Otherwise, continue to remove the top of the stack, the stack is empty or until the top of the stack height of the rectangle rectangle smaller than the current. In the stack process, we have accumulated is ejected and width of the rectangle, and each pops up a rectangle, to use its height multiplied by the width of the cumulative update answer. After the whole process the stack, we highly as the current height of the rectangle, the width of the rectangle for the new cumulative value of the stack.

AC Code:
#include<bits/stdc++.h>

using namespace std;
int h[25000];
int main(){
    int n;
    cin>>n;
    int maxn=0;
    for(int i=1;i<=n;i++){
        scanf("%d",&h[i]);
        maxn=max(maxn,h[i]);
    }    
    deque<int> q;
    for(int i=1;i<=n;i++){
        if(q.empty()){    // 
            q.push_back(h[i]);
            continue;
        }
        if(h[i]>=q.back()){  
            q.push_back(h[i]);
            continue;
        }
        int num=0;
        while(!q.empty()&&q.back()>h[i]){
            num++;
            int t=q.back();q.pop_back();
            maxn=max(maxn,t*num);
        }
        num++;
        while(num){
            q.push_back(h[i]);
            num--;
        }
    }
    int num=0;
    while(!q.empty()){
        num++;
        int temp=q.back();q.pop_back();
        maxn=max(num*temp,maxn);
    }
    printf("%d\n",maxn);
    return 0;
} 

 

Guess you like

Origin www.cnblogs.com/pengge666/p/11495379.html