Sunday, 4 October 2015

***Largest Rectangle in a Histogram(divide concure +segtree)

Problem H: Largest Rectangle in a Histogram

Source file: histogram.(c|cc|hs|java|pas)
Input file: histogram.in
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 Specification
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 Specification
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

-------------------------------------------editiorial------------------------------------

Largest Rectangular Area in a Histogram | Set 2

Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have same width and the width is 1 unit.
For example, consider the following histogram with 7 bars of heights {6, 2, 5, 4, 5, 2, 6}. The largest possible rectangle possible is 12 (see the below figure, the max area rectangle is highlighted in red)
histogram
We have discussed a Divide and Conquer based O(nLogn) solution for this problem. In this post, O(n) time solution is discussed. Like the previous post, width of all bars is assumed to be 1 for simplicity. For every bar ‘x’, we calculate the area with ‘x’ as the smallest bar in the rectangle. If we calculate such area for every bar ‘x’ and find the maximum of all areas, our task is done. How to calculate area with ‘x’ as smallest bar? We need to know index of the first smaller (smaller than ‘x’) bar on left of ‘x’ and index of first smaller bar on right of ‘x’. Let us call these indexes as ‘left index’ and ‘right index’ respectively. We traverse all bars from left to right, maintain a stack of bars. Every bar is pushed to stack once. A bar is popped from stack when a bar of smaller height is seen. When a bar is popped, we calculate the area with the popped bar as smallest bar. How do we get left and right indexes of the popped bar – the current index tells us the ‘right index’ and index of previous item in stack is the ‘left index’. Following is the complete algorithm.
--
1) Create an empty stack.
2) Start from first bar, and do following for every bar ‘hist[i]’ where ‘i’ varies from 0 to n-1. ……a) If stack is empty or hist[i] is higher than the bar at top of stack, then push ‘i’ to stack. ……b) If this bar is smaller than the top of stack, then keep removing the top of stack while top of the stack is greater. Let the removed bar be hist[tp]. Calculate area of rectangle with hist[tp] as smallest bar. For hist[tp], the ‘left index’ is previous (previous to tp) item in stack and ‘right index’ is ‘i’ (current index).
3) If the stack is not empty, then one by one remove all bars from stack and do step 2.b for every removed bar.
Following is C++ implementation of the above algorithm.
---------------------------------------stack code-------------------------------------------------------------------------------------------------
// C++ program to find maximum rectangular area in linear time
#include<iostream>
#include<stack>
using namespace std;
// The main function to find the maximum rectangular area under given
// histogram with n bars
int getMaxArea(int hist[], int n)
{
// Create an empty stack. The stack holds indexes of hist[] array
// The bars stored in stack are always in increasing order of their
// heights.
stack<int> s;
int max_area = 0; // Initalize max area
int tp; // To store top of stack
int area_with_top; // To store area with top bar as the smallest bar
// Run through all bars of given histogram
int i = 0;
while (i < n)
{
// If this bar is higher than the bar on top stack, push it to stack
if (s.empty() || hist[s.top()] <= hist[i])
{
s.push(i++);
           //  cout<<" jsut push "<<endl;
}
// If this bar is lower than top of stack, then calculate area of rectangle 
// with stack top as the smallest (or minimum height) bar. 'i' is 
// 'right index' for the top and element before top in stack is 'left index'
else
{
tp = s.top(); // store the top index
s.pop(); // pop the top
// Calculate the area with hist[tp] stack as smallest bar
area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1);
// update max area, if needed
if (max_area < area_with_top)
max_area = area_with_top;
}
}
// Now pop the remaining bars from stack and calculate area with every
// popped bar as the smallest bar
// cout<<i<<endl;
while (s.empty() == false)// remaining elements in the stack are just continuous increasing elements
{                        // so  this shows for any element tp , all elenment left to to are small , and right are bigger
tp = s.top();
s.pop();
// cout<<hist[tp] <<" ";
area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1);
if (max_area < area_with_top)
max_area = area_with_top;
}
return max_area;
}
// Driver program to test above function
int hist[1000000];
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++) cin>>hist[i];
cout <<getMaxArea(hist, n)<<endl;
return 0;
}
---------------------------------------------seg tree+ dividconcure  approach--------------------------------------------------------------------------------

Largest Rectangular Area in a Histogram | Set 1


Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have same width and the width is 1 unit.
For example, consider the following histogram with 7 bars of heights {6, 2, 5, 4, 5, 2, 6}. The largest possible rectangle possible is 12 (see the below figure, the max area rectangle is highlighted in red)
histogram
simple solution is to one by one consider all bars as starting points and calculate area of all rectangles starting with every bar. Finally return maximum of all possible areas. Time complexity of this solution would be O(n^2).
We can use Divide and Conquer to solve this in O(nLogn) time. The idea is to find the minimum value in the given array. Once we have index of the minimum value, the max area is maximum of following three values. a) Maximum area in left side of minimum value (Not including the min value) b) Maximum area in right side of minimum value (Not including the min value) c) Number of bars multiplied by minimum value. The areas in left and right of minimum value bar can be calculated recursively. If we use linear search to find the minimum value, then the worst case time complexity of this algorithm becomes O(n^2). In worst case, we always have (n-1) elements in one side and 0 elements in other side and if the finding minimum takes O(n) time, we get the recurrence similar to worst case of Quick Sort. How to find the minimum efficiently? Range Minimum Query using Segment Tree can be used for this. We build segment tree of the given histogram heights. Once the segment tree is built, all range minimum queries take O(Logn) time. So over all complexity of the algorithm becomes.
Overall Time = Time to build Segment Tree + Time to recursively find maximum area
Time to build segment tree is O(n). Let the time to recursively find max area be T(n). It can be written as following. T(n) = O(Logn) + T(n-1) The solution of above recurrence is O(nLogn). So overall time is O(n) + O(nLogn) which is O(nLogn).
Following is C++ implementation of the above algorithm.
-----------------------------------------------------code-----but in strict time limit this soln does not pass --------------------------------------------------------------------------------------
#include<bits/stdc++.h> using namespace std; typedef long long int lli; #define test() int test_case;cin>>test_case;while(test_case--) #define fr(i,n) for(int i=0;i<n;i++) #define frr(i,a,n) for(int i=a;i<n;i++) #define sll(a) scanf("%lld",&a) #define sl(a) scanf("%ld",&a) #define si(a) scanf("%i",&a) #define sd(a) scanf("%ld",&a) #define sf(a) scanf("%f",&a) #define rn(a) return a #define pai pair<int,int> #define pal pair<li,li> #define pall pair<lli,lli> #define ff first #define ss second #define mod 1000000007 #define mp make_pair #define pb push_back #define pll(a) printf("%lld\n",a) #define pl(a) printf("%lld\n",a) #define pi(a) printf("%d\n",a) #define pd(a) printf("%lf\n",a) #define pf(a) printf("%f\n",a) #define lc (start+end)/2 #define rc lc+1 #include<iostream> lli ans=0; int n; using namespace std; lli arr[1010000]; struct abcd { int val; int index; }tree[1010000]; int laz[10100000]; #define inf 999999999 abcd query(int node,int start,int end,int r1,int r2) { if(r1>end || r2<start || start>end) { abcd node; node.index=INT_MAX; node.val=INT_MAX; return node; } if(r1<=start && r2>=end) { return tree[node]; } else { abcd q1=query(2*node,start,(start+end)/2,r1,r2); abcd q2=query(2*node+1,((start+end)/2)+1,end,r1,r2); if(q1.val<=q2.val)return q1; else return q2; } } void build(int node , int start,int end) { //cout<<" build start "<<start<<" "<<end<<endl; if(start>end) return ; if(start==end) { tree[node].index=start; tree[node].val=arr[start]; } else { build(2*node,start,(start+end)/2); build(2*node+1,((start+end)/2)+1,end); if(tree[2*node].val<=tree[2*node+1].val) { tree[node].val=tree[2*node].val; tree[node].index=tree[2*node].index; } else { tree[node].val=tree[2*node+1].val; tree[node].index=tree[2*node+1].index; } } } int t=10; lli solve(int start,int end) { //if(t--==0) exit(0); lli ans=0; // cout<<"solve in the range "<<start<<" "<<end<<endl; if(start==end) { ans=max(ans,arr[start]); return ans; } else if(start>end) { return 0 ; } else { abcd node=query(1,0,n-1,start,end); int index=node.index; // cout<<" index"<<index<<endl; if(index==start) { // cout<<"ans set here "<<(end-start+1)*arr[index]; ans=max(ans,max((end-start+1)*arr[index],solve(index+1,end))); } else if(index==end) { ans=max(ans,max(ans*(end-start+1)*arr[index],solve(0,end-1))); } else { ans=max(ans,max((end-start+1)*arr[index],max(solve(start,index-1),solve(index+1,end)))); } return ans; } return ans; } int main() { cin>>n; for(int i=0;i<n;i++) { cin>>arr[i]; } // cout<<" before bouid "; build(1,0,n-1); // cout<<"after build "<<endl; int fin=solve(0,n-1); cout<<fin<<endl; }

No comments:

Post a Comment