[Template] dichotomous answer

1. Scene

Dichotomous answer is generally used in solving the qualifying minimum or maximum value above, when we encounter these two problems can generally be using the binary answer to solve the problem.

2. What is half the answer

The answer is by half of all possible answers range binary search, shrinking range, to finalize the method of the answer.

3. for the minimum

//求最小值
int binary(int left, int right) {
    int mid;
    while(left < right) {
        mid = (right + left) / 2;
        if (check(mid)) right = mid;
        else left = mid + 1;
    }
    return left;
}

We can know that the minimum requirements, then the value is assigned to meet the conditions of the right border, plus one does not meet the values assigned to the left margin when left == rightor left > rightwhen, then the query has to conform to the minimum.

4. selecting the maximum value

//求最大值
int binary(int left, int right) {
    int mid;
    while(left < right) {
        mid = (right + left + 1) / 2;
        if (check(mid)) left = mid;
        else right = mid - 1;
    }
    return left;
}

Similarly, the maximum requirements, then we need to give up qualifying smaller value, is about to meet the requirements of the assignment left boundary point, the right boundary of the value of the assignment is not eligible for a reduction. Constantly poll continues, the last remaining qualifying maximum. Which mid = (right + left + 1) / 2is to prevent an infinite loop, because when left = right + 1the time exactly in line with the conditions, left = (right + left) / 2will infinite loop.

5. check function concepts

Since we have chosen to use dichotomy to solve, then we are in check, it should be in case we know the answer continues to confirm the answer, that is not envisaged from the general direction of thinking, but verify. check function is often based on the assumption know the answer, to verify correct.

Guess you like

Origin www.cnblogs.com/szdytom/p/binary_search.html