Explain the binary search logic in 991C

Revision en2, by icode_247, 2018-08-29 21:01:36

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;
}
Tags 991c, #binary search

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English icode_247 2018-08-29 21:01:36 19
en1 English icode_247 2018-08-29 21:00:00 1198 Initial revision (published)