Binary integer correct Open

Reference: algorithm contest, this $ Blog $

Feel-half has stumbled, and finally to write a summary spicy

 

 Total speaking, there are two writing:

  1. Record the answers

  2. The record does not answer

 There are three segments:

  1. Record the answer (about the border which is the answer to almost all)

  2. Do not record their answers and find the minimum legal solution

  3. Do not record their answers and looking for the biggest legal solution (the most error-prone !!)

 

Here to talk about three kinds of specific segments

 1. Record the answers

// find the maximum legal solution of

the while
(L <= R & lt) { int MID = (L + R & lt) >> . 1 ; IF (Check (MID)) = MID ANS, L = MID + . 1 ; the else R & lt mid- = . 1 ; } the printf ( " % D \ n- " , ANS);
// find the minimum legal solution of

the while
(L <= R & lt) { int MID = (L + R & lt) >> . 1 ; IF (Check (MID)) ANS = MID, R & lt mid- = . 1 ; the else L = MID + . 1 ; } the printf ( " % D \ n- " , ANS);

 2 . Does not record the answers and find the minimum legal solution

while(l<r)
{
    int mid=(l+r)>>1;
    if(check(mid))r=mid;
    else l=mid+1;
}
printf("%d\n",l);

 3. Do not record their answers and looking for the biggest legal solution

$ The Attention! $ = MID this must be $ (L + R & lt + . 1 ) >>. 1 $

Consider a case where: $ r = l + 1, mid = (l + r) >> 1 = l $, $ l $ legitimate, $ l = mid = l $, then an endless loop

while(l<r)
{
    int mid=(l+r+1)>>1; //!Attention!
    if(check(mid))l=mid;
    else r=mid-1;
}
printf("%d\n",l);

 

Points of Attention and expand

1. take different forms corresponding MID $ $ emulated

2. Take 1 >> $ $ $ instead of / 2 $. This is because the right shift operation is rounded down to the integer division is $ 0 $ rounding error when two domain comprises a negative value.

3. (For the latter two approaches in terms) for two points in the free solution where: the between the first two partitions $ [1, n] $ extended to $ [0, n + 1] $, if half terminates stays in extended Solutions of no node

 

Talk so much I think it is the best first approach, much less consider:)

 

Guess you like

Origin www.cnblogs.com/forward777/p/11274599.html