Two point answer template

[Template + Explanation] Two-point answer

! Reading Instructions ||Before reading this blog post, I think that readers have learned (or understood):
1. Basic language and algorithm
2. Standard dichotomy (dichotomy)
3. Binary search

definition

The binary answer is similar to the binary search, that is, the monotonic answer is divided into two, and in most cases, it is used to find the maximum (small) value that satisfies a certain condition.

answer monotonicity

write picture description here
The monotonicity of the answer can be transformed into a function in most cases, and its monotonicity is proved in various ways, as follows:

  1. The more stones you move, the bigger the answer (NOIP2015 Jumping Stones).
  2. The condition of the first i day must be easier than the condition of the first i + 1 day (NOIP2012 borrowed classroom).
  3. It is easier to meet fewer allocation requirements than more (NOIP2010 Imprisonment of Offenders).
  4. It is easier to meet requirements for larger maximums than for smaller ones (NOIP2015 Shipping Plan).
  5. The longer the time, the easier it is to meet the conditions (NOIP2012 epidemic control).

Problems that can be solved

  1. Find the largest and smallest values ​​(NOIP2015 jumping stones).
  2. Find the minimum maximum value (NOIP2010 detains criminals).
  3. Find the smallest (largest) value that satisfies the condition.
  4. Find the value closest to a value.
  5. Find the minimum cost that satisfies the condition.

code

In order to ensure that the solution is in the interval of the binary search, different problems have different (but similar) ways of writing. The reader can draw an interval to simulate it~

find the minimum value

int binary()
{
    int l = 0, r = ll, mid;
    while(l < r)
      {
        mid = (l + r) >> 1; if(check(mid)) r = mid; //大多数题只要改改check()即可 else l = mid + 1; } return l; }

 

find the maximum value

int binary()
{
    int l = 0, r = ll, mid;
    while(l < r) { mid = (l + r + 1) >> 1; if(check(mid)) r = mid - 1; else l = mid; } return l; }

 

Universal dichotomy in the face of integers (approximately universal)

int binary(int n)
{
    int l = 1, r = maxn, ans = 0; while(l <= r) { int mid = (l + r) >> 1; if(c[mid] > a[n]) ans = mid, l = mid + 1; //判断条件与ans记录位置因题而异 else r = mid - 1; } return ans; }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325047193&siteId=291194637