Friday, 25 September 2015

Number List .. stock spain problem

Number List

https://www.hackerrank.com/challenges/number-list
similar prob chef 
https://www.codechef.com/AUG15/problems/DCGAME/

Problem Statement
Shashank loves to play with arrays a lot. Today, he has an array A consisting of N positive integers. At first, Shashank listed all the subarrays of his array A on a paper and later replaced all the subarrays on the paper with the maximum element present in the respective subarray.
For eg: Let us consider the following array A consisting of three elements.
A = {1,2,3}
List of Subarrays:
{1}
{2}
{3}
{1,2}
{2,3}
{1,2,3}
Final List:
{1}
{2}
{3}
{2}
{3}
{3}
Now, Shashank wondered how many numbers in the list are greater than K.
Input Format
The first line of input contains a single integer T denoting the number of test cases. The first line of each test case contains two space-separated integers, N and K, where N denotes the number of elements in the array A. The next line of each test case contains N space separated integers, each denoting an element of array A.
Constraints 
1T105 
1N2×105 
1Ai109 
0K109 
Sum of N over all test cases does not exceed 106.
Output Format
For each test case, Print the required answer in a separate line.
Sample Input
2
3 2
1 2 3 
3 1 
1 2 3 
Sample Output
3
5
Explanation
In the first test case, there are 3 numbers in the list greater than 2
In the second test case, there are 5 numbers in the list greater than 1.
---------------------------------------------for   good editorial -- see chef solution of this prob--------------------------------------
#include<iostream>
using namespace std;
typedef long long int lli;
#include<bits/stdc++.h>
#define maxi 10000000000




lli value[300100];
lli rit[300000];

lli lft[300000];

 int main()
  {
  freopen("abc.txt","r",stdin);
  int t;
   cin>>t;
   
   while(t--)
   {
    stack<pair<lli,lli> > stac,stac2;
   
    vector<lli> val;
 
   
  lli n,q;
   cin>>n;
   cin>>q;
   
   
      for(int i=0;i<n;i++)
       { 
         cin>>value[i];
        
}
 
     for(int i=n-1;i>=0;i--)
      {
     
        lli num=1;
 while(!stac2.empty() && value[i]>stac2.top().first)
{
num+=stac2.top().second;
stac2.pop();   
}
    rit[i]=num-1;
  
  
stac2.push(make_pair(value[i],num));
     
  }
  
  
  for(int i=0;i<n;i++)
 {
 
   lli num=1;
   while(!stac.empty() && value[i]>=stac.top().first)
    {
   
        num+=stac.top().second;
        stac.pop();
        
}
lft[i]=num-1;
stac.push(make_pair(value[i],num));
 
 }
 
 
  vector<pair<lli,lli> >tot;
  
  for(int i=0;i<n;i++)
   {
  
    tot.push_back(make_pair(value[i],rit[i]+lft[i]+1+rit[i]*lft[i]));
   
}
sort(tot.begin(),tot.end());
vector<lli> toti;
toti.push_back(tot[0].second);
val.push_back(tot[0].first);
for(int i=1;i<n;i++)
{
 
toti.push_back(toti[i-1]+tot[i].second);
val.push_back(tot[i].first);
}
  vector<lli > :: iterator aces;
 
aces=upper_bound(val.begin(),val.end(),q);
 
if(aces==val.begin())
 {
 
  lli timess=toti[n-1];
   cout<<timess<<endl;
  }
  else if(aces==val.end())
   {
   cout<<"0"<<endl;
}
else
{
 
lli  place=aces-val.begin();
place--;
 
 lli timess=toti[n-1]-toti[place];
 cout<<timess<<endl;
}
 
}
  return 0;
  } 
-------------------------------------------------chefs editorial---------------------------------------------------

PREREQUISITES:

stock span problem, stack, binary search, value compression, combinatorics

PROBLEM:

Given an array [A1,,AN]. Let B be the list of maximums of all subarrays of A (B has length N(N+1)2). Mgames will be played, each with a single constraint of the form "C K", where C is either <=>, and K is an integer. In a single game, players alternate turns, and in a move a player marks off an integer in B satisfying the constraint "C K", and the player with no more valid moves is the loser.
You have to determine the winner of each game.

QUICK EXPLANATION:

Each game depends only on the parity of the number of integers satisfying the constraint. Thus, we only need to find the number of values in B satisfying the constraint.
Let Li be the largest index Li<i such that ALiAi (set Li=0 if no such value exists)
Let Ri be the smallest index Ri>i such that ARi>Ai (set Ri=N+1 if no such value exists)
All Lis and Ris can be computed in O(N) using a stack.
There can be at most N distinct values in A, say [V1,,VM] with MN (in sorted order). Let f(j) be the number of subarrays in which Vj is the maximum. Then f(j)=Ai=j(Rii)(iLi).
There are three kinds of constraints "<K", "=K" and ">K". we need to know the sum of the f(j) for all j in which Vj satisfies the constraint. We introduce a fourth kind of constraint, "K". The other three kinds of constraints can be reduced to this.
To answer a "K" constraint, first find the largest index j such that VjK (with binary search). Then the result we want is f(1)++f(j). This number can quickly be obtained if we precompute all prefix sums beforehand.

EXPLANATION:

The solution has multiple parts. We start with the most obvious questions first, so that we know what to precompute, etc.

A "game"

Let's first discuss how a game occurs. Suppose we have the list B, which contains the N(N+1)2 maximums among all subarrays (of course, we can't construct this array in the harder subtasks because of its size). The first thing to notice is that the order of B's elements doesn't matter. Thus, we can assume that B is sorted.
Let's first assume that we have a constraint. The key thing to notice is that the game is really simple: the players simply alternate turns marking off numbers in B satisfying the constraint. In fact, the winner is solely dependent on the number of values in B satisfying the constraint, i.e., it doesn't matter whatever strategy both players are using! To be specific:
  • If there are an even number of such numbers, then the second player always moves last.
  • If there are an odd number of such numbers, then the first player always moves last.
Therefore, we only need to count those elements of B satisfying the constraint! Because B is sorted and because of the nature of the constraints, this number can be computed using one or two binary searches!
To illustrate, let I(K) be the number of elements of B that are K (or simply the index of the largest i such that BiK, which can be computed with a binary search). Then:
  • The number of elements of B that are <K is I(K1).
  • The number of elements of B that are =K is I(K)I(K1).
  • The number of elements of B that are >K is N(N+1)2I(K).
Thus, if we already have the array B, then we can easily compute the result of any game in O(log(N(N+1)2))=O(logN) time.

Run-length encoding

Unfortunately, the previous approach uses up O(N2) memory because of the array B. But we can reduce this significantly by noticing that there are only at most N distinct values in B. (Why?) So let [V1,,VM] be the distinct values in B, and let f(i) be the number of occurrences of Vi in B.
We can then compute I(K) by doing a binary search in V instead for the largest i such that ViK, and then I(K)is simply f(1)+f(2)++f(i). If we precompute all prefix sums of the f(i), then I(K) can still be computed in O(logN) time, but the memory requirements decrease to just O(N).

Computing V and f(i)

To complete the algorithm, we need to compute the array [V1,,VM] and the values f(1),,f(M). Note that the sequence V can be computed in O(NlogN) time from the array A (with a simple sort + uniquify operation). Thus, all that remains is to compute the f(i)s.
First, let's suppose that all elements of A are distinct. Consider the value Ai. How many subarrays are there whose maximum is Ai? Well, let Li and Ri are the nearest larger elements to the left and right of Ai, respectively. Then the subarray cannot contain either ALi or ARi. Thus, the subarray should be strictly contained in [ALi+1,,ARi1], but due to the way Li and Ri are defined, we see that the latter condition is sufficient. Thus, there are (Rii)(iLi) possible subarrays (there are (Rii) and (iLi) ways to choose the right and left endpoints, respectively). Let us denote this quantity by m(i).
As an example, consider the following image (Ai is the height of the bar over the number i):
#             
#             #
#       #     #
#   #   #     #
#   #   # #   #
# # #   # #   #
# # #   # # # #
# # # # # # # #
1 2 3 4 5 6 7 8
In this case, suppose i=5. Then Li=1 and Ri=8. Thus, there are (Rii)=3 and (iLi)=4 choices for the right and left endpoints, respectively, for a total of 3×4=12 subarrays, as shown below:
1 2 3 4 5 6 7 8
 (2 3 4 5)
   (3 4 5)
     (4 5)
       (5)
 (2 3 4 5 6)
   (3 4 5 6)
     (4 5 6)
       (5 6)
 (2 3 4 5 6 7)
   (3 4 5 6 7)
     (4 5 6 7)
       (5 6 7)
As a consequence, we have f(j)=m(i) for the (unique) i such that Ai=Vj.
In case either Li or Ri doesn't exist, we can use the values 0 or N+1, respectively.
This formula, and the expression m(i)=(Rii)(iLi) is nice; unfortunately it doesn't extend straightforwardly if the Ais are not all distinct. To see why, consider the following example:
#         #     #
#   #   # #   # #
# # #   # #   # #
# # # # # # # # #
1 2 3 4 5 6 7 8 9
The natural extension of f(j)=m(i) would be f(j)=Ai=Vjm(i). However, in the above case, it doesn't quite work. Consider j=3. There are three is with Ai=3, namely i=3i=5 and i=8. But we have m(3)=6m(5)=6 and m(8)=2, so according to this formula this gives f(3)=6+6+2=14. However, the correct value of f(3) is 10! (verify) Clearly we need to fix this formula.
We can do that by redefining m(i) so that it counts the subarrays whose leftmost maximum is Ai. This uses the fact that each subarray has a unique leftmost maximum, so no subarray is double-counted. To implement this, redefine Liby weakening it so that ALi can equal Ai (i.e. ALiAi). Then m(i) stays the same, i.e. (Rii)(iLi). In the example above, we get the new values m(3)=6m(5)=2 and m(8)=2, so f(3) is correctly computed as 6+2+2=10.
But how do we compute the Lis and Ris? Actually, these values can be computed easily in O(N) time by means of a stack: it's actually a standard problem called the stock span problem. (Recognizing this as the stock span problem requires experience, but if you didn't know about this, notice that the problem of computing the Lis and Ris can be done in O(NlogN) time with a segment tree)
Now, all that remains is to compute the f(i)s given the m(i)s. But this can be done easily in linear time also:
  • Create an array for f, all initialized to zero.
  • Create an inverse map of V, say ϕ, where ϕ(Vi)=i.
  • For every 1iN, add the value m(i) to f(ϕ(Ai)).
That's it! We now have all the parts needed for the whole solution. The preprocessing takes O(NlogN) time, and each query can be answered in O(logN) time! The following is an example implementation in C++:

No comments:

Post a Comment