Wednesday, 7 October 2015

**Little Elephant and Cards

 Little Elephant and Cards
The Little Elephant loves to play with color cards.
He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).
Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 — colors of both sides. The first number in a line is the color of the front of the card, the second one — of the back. The color of the front of the card may coincide with the color of the back of the card.
The numbers in the lines are separated by single spaces.
Output
On a single line print a single integer — the sought minimum number of moves. If it is impossible to make the set funny, print -1.
Sample test(s)
input
3
4 7
4 7
7 4
output
0
input
5
4 7
7 4
2 11
9 7
1 1
output
2
Note
In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.
In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7.

--------------------------------------------editorial---------------------------------------------------------------------------
It is nice to use the map structure in this problem, but you can solve it without map (using sorting and binary serach). Lets iterate through all possible colors that we have and suppose that this currect color is the one that will make our set funny. The minimal number through all this will be the answer. To find the minimal number of turns to make our set funny using current color we need to know two numbers: the number of cards with current color on the front side and the number of cards with the current color on back side (but not at the same time). Let it be integers a and b. Let m = (n + 1) / 2 — the minimal number of the same cards required to get the funny set. Then if a + b < m it is impossible to make set funny using current color at all. If a ≥ m then the answer is 0, otherwise the answer ism - a.

--------------------------------------------------------code---------------------------------------------------------------------
implementation is easy ..
only tricky thing is that there may  be possibility a card which is not in front side but  , it can made answer. because on opposite side its enough pairs are available ..

------------------------------------------code----------------------------------------------------------------------------------
#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 second 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
int main()
 {
  int n;
   cin>>n;
   vector<pall> v;
   vector<lli> v1;
   map<lli,int> back;
   set<lli> s;//  will contain all distinct colour which can be give answer 
   
   for(int i=0;i<n;i++)
    {
    lli a,b;
     cin>>a>>b;
     
     s.insert(a);
     s.insert(b);
     
     v.pb(mp(a,b));
     
     v1.pb(a);// it used for applying b'search since not applicable on vector<pair>
     
     
     
    if(a!=b)// means there is some card of different colour on opposoit side
           // which can be used after swap, eliminate a==b sice if both side card are same
           // colour than no meaning of togling
     {
       
      back[b]++;
     
 }
     
}
sort(v.begin(),v.end());
sort(v1.begin(),v1.end());
int mini;
if(n%2==1) mini=n/2+1;
else
mini=n/2;

 
  int ans=INT_MAX;
  set<lli> :: iterator its;
 
  for(its=s.begin();its!=s.end();its++)
  {
  vector<lli> :: iterator it,itv;
    lli clr=*its;
 
    itv=lower_bound(v1.begin(),v1.end(),clr);
    it=upper_bound(v1.begin(),v1.end(),clr);
    int temp=it-v1.begin();
    it--;
    int cov=it-itv+1;
 
    if(cov>mini)
     {
      cout<<"0";
      return 0;
 }
 else
 {
  int req=mini-cov;
  if(req<=back[*its])
  ans=min(ans,req);
 
 }
 
    
 }
 if(ans!=INT_MAX)
 cout<<ans<<endl;
 else
 cout<<"-1"<<endl;
 return 0 ;
 }

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

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