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
A 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; }

Thursday, 1 October 2015

(divid_concure)Connecting Soldiers

Connecting Soldiers




All submissions for this problem are available.

To protect people from evil, a long and tall wall was constructed a few years ago. But just a wall is not safe, there should also be soldiers on it, always keeping vigil. The wall is very long and connects the left and the right towers. There are exactly N spots (numbered 1 to N) on the wall for soldiers. The Kth spot is K miles far from the left tower and (N+1-K) miles from the right tower.
Given a permutation of spots P of {1, 2, ..., N}, soldiers occupy the N spots in that order. The P[i]th spot is occupied before the P[i+1]th spot. When a soldier occupies a spot, he is connected to his nearest soldier already placed to his left. If there is no soldier to his left, he is connected to the left tower. The same is the case with right side. A connection between two spots requires a wire of length equal to the distance between the two.
The realm has already purchased a wire of M miles long from Nokia, possibly the wire will be cut into smaller length wires. As we can observe, the total length of the used wire depends on the permutation of the spots P. Help the realm in minimizing the length of the unused wire. If there is not enough wire, output -1.

Input

First line contains an integer T (number of test cases, 1 ≤ T ≤ 10 ). Each of the next T lines contains two integers N M, as explained in the problem statement (1 ≤ N ≤ 30 , 1 ≤ M ≤ 1000).

Output

For each test case, output the minimum length of the unused wire, or -1 if the the wire is not sufficient.

Example

Input:
4
3 8
3 9
2 4
5 25

Output:
0
0
-1
5


Explanation:
In the 1st case, for example, the permutation P = {2, 1, 3} will use the exact 8 miles wires in total.

In the 2nd case, for example, the permutation P = {1, 3, 2} will use the exact 9 miles wires in total.

To understand the first two cases, you can see the following figures:






In the 3rd case, the minimum length of wire required is 5, for any of the permutations {1,2} or {2,1}, so length 4 is not sufficient.

In the 4th case, for the permutation {1, 2, 3, 4, 5} we need the maximum length of the wire = 20. So minimum possible unused wire length = 25 - 20 = 5.

-------------------------------------------------------------------------editorial--------------------------------------------------------------

PREREQUISITES

arrays, divide-and-conquer, recursion

PROBLEM

Given an array A[0..N+1], consider the indices [1..N] as spots for the soldiers and index 0 as the left tower and the index N+1 as the right tower. Initially set A[0] = 1, A[N+1] = 1 and rest all have 0s. Given a permutation P[1..N] of the indices {1, 2,...,N}, we fill them with 1s in that order and find the length of used wire as follows.
used_length = 0 for i = 1 to N used_length += ( distance from index P[i] to nearest index having 1 to left ); used_length += ( distance from index P[i] to nearest index having 1 to right ); A[ P[i] ] = 1;
You can see that the used_length depends on the permutation P and given an integer M, we need to find the minimum length of unused wire. It is same as asking for the maximum possible used_length ≤ M for some permutation P. If M is not sufficient for any permutation P, output -1.

QUICK EXPLANATION

If you have solved the problem or almost got it yourself, this explanation is for you. If you have not solved it and eager to know how to build the idea from scratch, skip this part and go to the Detailed explanation section below.
There is a simple bruteforce solution and other clever solution. They are explained below.
  1. N = 30 is so small that you can generate all possible used_lengths for each N = 1 to 30. For a given N, we just need to fix the first position and that partitions the problem in to two independent smaller subproblems and we can merge the answers to these smaller subproblems. If we consider the number of possible used_lengths for a given N to be of order O(N2), this requires time O(N5), which is fast enough for N = 30.
  2. Given N, we can find the minimum and maximum used_lengths.
For minimum, its always better to try partitioning the problem into two equal subproblems.
minLen[n] = (n+1) + minLen[n/2] + minLen[n-1-n/2](easy divide and concure )
For maximum, we just need to place in the order {1,2,3...N}
maxLen[n] = (n+1) + maxLen[n-1] , this is same as maxLen[n] = (n*(n+3))/2
Now, can you prove that all the values between [ minLen[n], maxLen[n] ] are possible ? An idea is given in tester's approach.

DETAILED EXPLANATION

If you haven't solved this problem yet, take some time now and try different cases on paper. eg. Consider N = 4 and try to find all possible sum_of_lengths for different permutations of {1,2,3,4}. You can also take a look at the explanation of sample cases under the problem statement for better understanding.
First lets see an almost bruteforce solution. Consider the array A for N = 9.
Initially A = |, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
and we need to fill the array with 1s in some order. Suppose if we set A[4] = 1,
then A = |, 0, 0, 0, 1, 0, 0, 0, 0, 0, |
and length of wire on left side = 4, length of wire on right side = 6, so we need wire of length 4 + 6 = 10.

Note that if we place the first soldier among N spots at any index, we need wire of length (N+1). Not only that, the first soldier now acts as a barrier between his left and right sides. There will never be a wire which cross this soldier. So we have two independent problems now. If the first solder is placed at index I, then we need (N+1) length wire for this soldier and solve subproblem with (I-1) spots on left side and subproblem with (N-I) spots on right side.
A = |, 0, 0, 0, 1, 0, 0, 0, 0, 0, | is same as solving
A = |, 0, 0, 0, | and |, 0, 0, 0, 0, 0, |

So we can store all possible values for each N = 1 to 30, and for a given N try all possible positions for the first soldier and mix the answers of the two independent subproblems to get all possible values. As the constraint on N is 30, you can just bruteforce each of these steps.

For an alternate simple approach, see point 2 in the quick explanation section.
-------------------------------------------------------------code-------------------------------------------------------
#include <stdio.h> int find_min (int n) { int first, last; if (n == 0) return 0; else { if (n & 1) first = last = n/2; else { first = n/2 - 1; last = n/2; } return ((n+1) + find_min(first) + find_min(last)); } } int main () { int T, M, N, min, max; scanf ("%d", &T); while (T--) { scanf ("%d %d", &N, &M); min = find_min(N); max = N * (N + 3) / 2; if (M < min) printf ("-1\n"); else if (M > max) printf ("%d\n", (M - max)); else printf ("0\n"); } return 0; }

Monday, 28 September 2015

****(vvi) Glass Carvin

 Glass Carvin

http://codeforces.com/problemset/problem/527/C

Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular wmm  ×  h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Sample test(s)
input
4 3 4
H 2
V 2
V 3
V 1
output
8
4
4
2
input
7 6 5
H 4
V 3
V 5
H 2
V 1
output
28
16
12
6
4
Note
Picture for the first sample test:
Picture for the second sample test:


--------------------------------------------------------------------------------------------------------------------------------------------
At any moment we realise that the maximum area is the product of the segment produced my max vertical length and maximum height 
We keep 4 sets that represent the following (1) Cuts at horizontal (2) Cuts at vertical (3) Length of vetical segments (4) width of horizontal segment initiall we push (0,w) to height and (0,h) to vertical then we push h to horizontal size array and w to vertical size array now when we make a cut horizontally clearly imagine the things taking place Suppose we cut at dist d (1) we try to find the position of the cut between to last cuts(initially it is between 0 and h) (2) we remove the piece (h-0) from the set that represents horizontal cut lengths(segments) (3) We insert two new segment of length (d1-0) & (h-d1) to the segments. Thus we see we are simulating the process taking place . The maximum are can be found by product of maximum horizontal length and maximum vertical length




---------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include<bits/stdc++.h> using namespace std; #define ll long long int int main() { int n; int w,h; cin>>w>>h>>n; multiset<int> cuth,cutw,maxh,maxw; cuth.insert(0); cuth.insert(h); cutw.insert(0); cutw.insert(w); maxh.insert(h); maxw.insert(w); int len; for(int i=0;i<n;i++) { char str[10]; cin>>str; cin>>len; if(str[0]=='H') { // cout<<"t 1 "<<endl; multiset<int>:: iterator it,it1,it2; it=cuth.lower_bound(len); // cout<<*it<<endl; it1=it; it1--; int val=*it-*it1; // cout<<"del "<<val<<endl; it2=maxh.lower_bound(val); maxh.erase(it2); cuth.insert(len); maxh.insert((len-*it1)); maxh.insert((*it-len)); } else { multiset<int>:: iterator it,it1,it2; it=cutw.lower_bound(len); it1=it; it1--; int val=*it-*it1; // cout<<"del val "<<val<<endl; it2=maxw.lower_bound(val); maxw.erase(it2); cutw.insert(len); maxw.insert((len-*it1)); maxw.insert((*it-len)); } //cout<<"done "<<endl; ll l1=*(maxw.rbegin()); ll l2=*(maxh.rbegin()); //cout<<l1<<" "<<l2<<endl; ll ans=l1*l2; cout<<ans<<endl; } return 0; }

Points on Line

 Points on Line
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen points doesn't matter.
Input
The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got.
It is guaranteed that the coordinates of the points in the input strictly increase.
Output
Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.
Please do not use the %lld specifier to read or write 64-bit integers in ะก++. It is preferred to use the cin, cout streams or the %I64dspecifier.
Sample test(s)
input
4 3
1 2 3 4
output
4
input
4 2
-3 -2 -1 0
output
2
input
5 19
1 10 20 30 50
output
1
Note
In the first sample any group of three points meets our conditions.
In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
In the third sample only one group does: {1, 10, 20}.

--------------------------------------------------------editorial----------------------------------------------------------------
Let's select the rightmost point of our triplet. In order to do this we can iterate over all points in ascending order of their X-coordinate. At the same time we'll maintain a pointer to the leftmost point which lays on the distance not greater than d from the current rightmost point. We can easily find out the number of points in the segment between two pointers, excluding the rightmost point. Let's call this number k. Then there exist exactly k * (k - 1) / 2 triplets of points with the fixed rightmost point. The only thing left is to sum up these values for all rightmost points.

----------------------------------------------------code------------------------------------------------------------------------
#include<bits/stdc++.h>
using namespace std;
typedef long long int lli;
typedef long int li;


 vector<lli> v;
  lli ans=0;
  
int main()
{
int n,d;
 cin>>n>>d;
 for(int i=0;i<n;i++)
  {
  lli a;
   cin>>a;
   v.push_back(a);
  }
  sort(v.begin(),v.end());
  for(int i=0;i<n-2;i++)
   {
    // cout<<" i "<<i<<endl;
        lli maxi;
    lli pre=v[i];
    // if(pre <0)
      maxi=pre+d;
       vector<lli> :: iterator it;
       it=upper_bound(v.begin()+i+2,v.end(),maxi);
       if(it==v.end() || *it-d>v[i]) it--;
      lli sets=it-v.begin()-i;
       // cout<<sets<<endl;
       ans+=(sets*(sets-1))/2;
      //  cout<<ans<<endl;
     
}
  
cout<<ans<<endl;
}