icode_247's blog

By icode_247, history, 6 years ago, In English

Hi, I am a bit confused in the kind of logic used in the problem 991C Candies. The tutorial says that I have to produce a K using binary search every time and then check if for that k the person consumes more than half of the total candies. But I couldnt understand how the K is being generated using binary search. Basically can someone please explain me the logic in details?

Thank you!.

Link to the problem click here The model solution from tutorial is given below:

#include <bits/stdc++.h>
 
using namespace std;
 
bool check(long long k, long long n) {
    long long sum = 0;
    long long cur = n;
    while (cur > 0) {
        long long o = min(cur, k);
        sum += o;
        cur -= o;
        cur -= cur / 10;
    }
    return sum * 2 >= n;
}
 
int main() {
    long long n;
    cin >> n;
 
    long long l = 1, r = n;
    long long ans = r;
    while (l <= r) {
        long long k = (l + r) / 2;
        if (check(k, n)) {
            ans = k;
            r = k - 1;
        }
        else
            l = k + 1;     }
 
    cout << ans << endl;
}
  • Vote: I like it
  • +8
  • Vote: I do not like it

| Write comment?
»
6 years ago, # |
  Vote: I like it +11 Vote: I do not like it

It should be easy to see, that the more candies Vasya eats every day, the more he will eat in total. E.g. you could compute an array a, where a[k] is the amount of candy that Vasya eats in total, if he eats k candies each day. This array is monotone increasing. Therefore you can do a binary search to find the point where he eats at least candies.

Now, generating this array is of course impossible (since n is quite big). But since binary search only accesses values of the array, we only need to know the values of these values, and we don't care about the other values at all. So you can just compute these few values on the fly.

In the code they do a normal binary search for the value k (the first position in the array with the value ). The function check then computes the value (e.g. computes how many candies Vasya eats in total for a given k), and compares it with .