You are on page 1of 2

PS-9 (Binary Search) Hints

A. Worms

-> Compute the prefix array of the n numbers to get upto the i-th pile, i.e., in total, how many
worms are there (note that worms will be labelled from 1 to a_1 + a_2 + ... and so on).

-> Find out the lower bound of each of the m labels using (lower_bound() function) and find
the corresponding index in the manner described in the lecture (simple subtraction!)

B. Interesting Drink

-> This question was taken up in the lecture, what we just need to do is sort the array of the
prices of the drinks. Then calculate the upper bound of the money that you have on a
particular day, calculate the corresponding index.

-> Remember this index will corresponding to the minimum index of the shop, in which you
cannot buy a drink. So, for maximum index of the shop in which you can buy a drink, is 1 less
than this index.

C. Ball Queries

-> In your code, to avoid TLE, add the following lines, at the beginning of your main() function:

ios_base::sync_with_stdio(false);

cin.tie(NULL);

cout.tie(NULL);

-> Sort the elements first

-> number of balls having weight less than x : calculate the index of lower bound of x and
subtract 1.

-> number of balls having weight less than or equal to x : calculate the index of upper bound
of x and subtract 1.

-> number of balls having weight greater than x : calculate the difference of indices of upper
and lower bounds of x.

D. Scuza

→ Compute the prefix sums of the array in each test case. Separately, maintain an array that
contains the maximum element of the array starting from 1 to the particular index.

→ We need to find the index of the minimum element where the maximum element is > k (the
number in each question) => use upper_bound() function! The prefix sum of the index which is
1 less than this number, will give you the maximum height upto which Timur can climb. If
there is NO element present, then output 0 in this case.

E. Save More Mice

→ Observe that the cat will always move to the right by 1 each time. It will go to 1, 2, ..., n - 1.
So, the mice have a maximum of n-1 moves. Now, for each mouse, compute the distances
from the hole at x = n, store it in an array and sort it.

→ Now, calculate the prefix sum of this array. Then just find out the upper bound of n - 1 in
this array, and subtract 1 (Basically, the total number of moves of the mice to x = n, should be
<= n-1).

F. Poisoned Dagger

->Let's find out the total damage for a fixed value of k. Since the effect of the poison from the
i-th attack deals damage min(k, a_{i+1} - a_{i}) seconds for i < n and k seconds for i = n, then
the total damage is the sum of [min(k, a_{i+1} - a_{i}) (=> from i = 1 to n-1) + k]. We can see that
the higher the value of k, the greater the total sum. So, we can do a binary search on k, and
find the minimum value when the sum is greater than or equal to h.

You might also like