HackerRank - largest-rectangle

Portal

The meaning of problems

Gives the n adjacent buildings, each building has a certain height, width are 1, the largest rectangular area calculating exist.

 

Thinking

The height of each rectangle can be used as building high, with L [i] and R & lt [i] in the i-th record of building the leftmost and rightmost range rectangular range that can be extended to a high.

 

Code

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<queue>
 4 using namespace std;
 5 const int maxn = 100000 + 5;
 6 
 7 int a[maxn], l[maxn], r[maxn];
 8 
 9 struct node{
10     int value, pos;
11     bool operator < (const node& rhs) const{
12         return value < rhs.value;
13     }
14 };
15 
16 int main(){
17     //freopen("in.txt", "r", stdin);
18     int n;
19     while(~scanf("%d", &n)){
20         for(int i=0; i<n; i++)  scanf("%d", &a[i]);
21 
22         priority_queue<node> q;
23         for(int i=0; i<n; i++){
24             while(!q.empty()){
25                 node s = q.top();
26                 if(s.value > a[i]){
27                     r[s.pos] = i-1;
28                     q.pop();
29                 }
30                 else if(s.value <= a[i]){
31                     break;
32                 }
33             }
34             node s;
35             s.value = a[i];
36             s.pos = i;
37             q.push(s);
38         }
39         while(!q.empty()){
40             node s = q.top();
41             q.pop();
42             r[s.pos] = n-1;
43         }
44 
45         for(int i=n-1; i>=0; i--){
46             while(!q.empty()){
47                 node s = q.top();
48                 if(s.value > a[i]){
49                     l[s.pos] = i+1;
50                     q.pop();
51                 }
52                 else if(s.value <= a[i]){
53                     break;
54                 }
55             }
56             node s;
57             s.value = a[i];
58             s.pos = i;
59             q.push(s);
60         }
61         while(!q.empty()){
62             node s = q.top();
63             q.pop();
64             l[s.pos] = 0;
65         }
66 
67         int res = -1;
68         for(int i=0; i<n; i++){
69             res = max(res, a[i]*(r[i]-l[i]+1));
70         }
71         printf("%d\n", res);
72     }
73     return 0;
74 }

 

Guess you like

Origin www.cnblogs.com/zyb993963526/p/12654296.html