Binary Searches-binary search

Source: Internet
Author: User

Binary search is a classical method of finding the target value in an ordered array, that is, the premise of using "ordered array". The "ordered" features in very simple questions are very obvious, but more often we need to construct "ordered arrays" ourselves. Below we start with the most basic binary search to step into.

First, Lower/upper bound

Defines lower bound as the smallest index in a given ascending array that is greater than or equal to the target value, upper bound is the maximum index less than or equal to the target value, and the following code and test case.

ImportJava.util.*; Public classMain { Public Static voidMain (string[] args) {int[] Nums =New int[]{1,2,2,3,4,6,6,6,13,18}; System.out.println (Lowerbound (Nums,6));//5System.out.println (Upperbound (nums, 6));//7System.out.println (Lowerbound (Nums, 7));//8System.out.println (Upperbound (Nums, 7));//7    }    /** Nums[index] >= target, min (index)*/     Public Static intLowerbound (int[] Nums,inttarget) {        if(Nums = =NULL|| Nums.length = = 0)return-1; intLB =-1, UB =nums.length;  while(lb + 1 <UB) {            intMID = lb + (ub-lb)/2; if(Nums[mid] <target) {lb=mid; } Else{UB=mid; }        }        returnLB + 1; }    /** Nums[index] <= target, max (index)*/     Public Static intUpperbound (int[] Nums,inttarget) {        if(Nums = =NULL|| Nums.length = = 0)return-1; intLB =-1, UB =nums.length;  while(lb + 1 <UB) {            intMID = lb + (ub-lb)/2; if(Nums[mid] >target) {UB=mid; } Else{lb=mid; }        }        returnUb-1; }}

SOURCE Analysis

lowerBoundFor example, the above two-point search template has several very elegant implementations:

    1. whileLoop lb + 1 < ub , not an equal sign, because taking an equal sign can cause a dead loop. When initializing lb < ub , there must be a last loop exit lb + 1 == ub .
    2. mid = lb + (ub - lb) / 2, it can effectively prevent the overflow after two number addition.
    3. lband initialization ub , initialized to both ends of the array, this initialization method is more than 0 and nums.length - 1 has a number of advantages, detailed below.

There are three typical scenarios when you encounter a location where you are asked to insert an index:

    1. The target value is within the range of the array, and the final return value must belb + 1
    2. The target value is smaller than the minimum value of the array, and is always the same, lb -1 so the final return lb + 1 is also true, you can also understand the array -1 before a smaller value
    3. The target value is greater than or equal to the last value of the array, because the loop exit condition is  lb + 1 == ub  , then the loop exits must have lb = A.length - 1 , should returnlb + 1

In summary, the return lb + 1 is a very elegant implementation. In fact, the above three kinds of situations can be unified as a way to understand, that is, the index -1 corresponds to a very small number in front of the array, the index ub is the corresponding array behind a very large number, then the number to be inserted must be in lb and ub between.

Sometimes complex boundary conditions can be handled skillfully in an elegant way such as "complement" .

With respect to the initialization of LB and UB, because mid = lb + (ub - lb) / 2 , and there is lb + 1 < ub , it is possible for the mid to be ub - 1 or not, the element that lb + 1 needs to be accessed mid + 1 or mid - 1 indexed may be out of bounds. At this point you need to change the initialization mode lb = 0, ub = A.length - 1 , and finally add a reference to lb, ub the index element of the judgment can be. such as Search for a Range and Find Peak Element. In particular, the initial values of LB and UB in the Find Peak Element can cause some trouble if initialized to 1 and array lengths.

Second, the optimal solution

In addition to searching for a very direct binary search in an ordered array, we can also use binary search to find the optimal solution (maximum/minimum), which is usually implicit in the "Ordered array", which requires our own construction.

The mathematical language to describe is "to satisfy a certain condition C (x) of the minimum/large X", in order to minimize the value for example, for any of the conditions of XXX, if all the X≤X′≤UBX \leq x^\prime \leq ubx≤x′≤ub for C (x′) C (x^\prime) C (x ) are true (which may be UB infinity, or the largest solution that satisfies the condition, if not satisfied with this condition can not guarantee the correctness of the binary search), then we can use a binary search to solve, where the initialization of the Nether is lb initialized to a value that does not meet the condition LB , The upper bound is initialized to the upper bound that satisfies the condition UB . Then in the while loop inside each fetch, satisfies the condition to take ub = mid , otherwise lb = mid , then finally ub is the request minimum value. The maximum value is similar, except that it is handled lb .

Take POJ no.1064 as an example.

Cable mastertime limit:1000ms Memory limit:10000ktotal submissions:66707 accepted:13737Descriptioninhabitants of the Wonderland has decided to hold a regional programming contest. The judging committee has volunteered and have promised to organize the most honest contest ever. It is decided to connect computers forThe contestants using a "star" topology-i.e. connect them all to a single central hub. To organize a truly honest contest, the Head of the judging committee have decreed to place all contestants evenly around T He hub on the equal distance from it. To buy network cables, the judging committee have contacted a local network solutions provider with a request to sell forthem a specified number of cables with equal lengths. The judging committee wants the cables to be asLongAs possible to sit contestants as far from each other as possible. The Cable Master of the company is assigned to the task. He knows the length of each cable in the "stock up" Centimeter,and he can cut them with a centimeter precision being to LD the length of the pieces he must cut. However, ThisTime , the length is not known and the Cable Master is completely puzzled. The Cable Master, by writing a program that would determine the maximal possible length of a Cable piece th At can is cut from the cables in the stock, to get the specified number of pieces. Inputthe first line of the input file contains the numb ers N and K, separated by a space. N (1 = N = 10000) is the number of cables in the stock, and k (1 = k = 10000) is the number of the requested pieces. The first line was followed by N lines with a number per line, which specify the length of each cable in the the stock in Mete Rs. All cables is at least 1 meter and at the most 100kilometers in length. All lengths in the input file is written with a centimeter precision, with exactly, and digits after a decimal point. Outputwrite to the output file, the maximal length (in meters) of the pieces, Cable Master may cut from the cables in T He stock to get the requested number of pieces. The number must is written with a centimeter precision, with exactly, and digits after a decimal point. If It isn't possible to cut the requested number of pieces each one being at least one centimeterLong, then the output file must contain the "0.00"(without quotes). Sample Input4 118.027.434.575.39Sample Output2.00

Problem

There are N ropes, the lengths of which are Li. If you cut a rope of the same length of k from them, how long will each of these k ropes last? The answer is reserved to two digits after the decimal point.

Input
= 4, L = {8.02, 7.43, 4.57, 5.39}, K = 11
Output

2.00

Exercises

This question seems to be an optimization problem, we try to use the idea of template two to solve, * * so C (x) c (x) c (x) is "can get KKK length of the Rope xxx." * * According to test instructions, we can further refine the above conditions to: C (x) =∑i (Floor (li/x)) ≥KC (x) = \sum_i (Floor (l_i/x)) \geq KC (x) =i∑ (Floor (li/x)) ≥k

Let us now analyze the upper and lower bounds of the feasible solution. Since the answer retains two digits after the decimal point, it is obvious that the length of the rope must be greater than 0, the minimum value of two bits after the decimal point is greater than 0, 0.01 obviously if the problem finally has a solution, it 0.01 must be the smallest feasible solution, and the solution can be divided by the maximum number of lines. Generally in the OJ of different variables will give the scope limit, then we will initialize the upper bound 最大范围 + 0.01 , it must be in the feasible solution outside (also can traverse the array to take the maximum value of the array, but in fact, the complexity of the difference between two points is not small). After using the binary search, the last return lb can be.

ImportJava.io.*;ImportJava.util.*; Public classMain { Public Static voidMain (string[] args) {Scanner in=NewScanner (system.in); intn =In.nextint (); intK =In.nextint (); Double[] Nums =New Double[n];  for(inti = 0; I < n; i++) {Nums[i]=in.nextdouble (); } System.out.printf ("%.2f\n", Math.floor (Solve (nums, k) * 100)/100); }     Public Static DoubleSolveDouble[] Nums,intK) {DoubleLB = 0.00, UB = 10e5 + 0.01; //While (lb + 0.001 < UB) {         for(inti = 0; I < 100; i++) {            DoubleMID = lb + (ub-lb)/2; if(C (Nums, Mid, K)) {lb=mid; } Else{UB=mid; }        }        returnlb; }     Public Static BooleanCDouble[] Nums,DoubleSegintk) {intCount = 0;  for(Doublenum:nums) {Count+ = Math.floor (num/seg); }        returnCount >=K; }}

SOURCE Analysis

method to C do only one thing, given an array nums , to determine whether it can cut the K length seg of the rope. The use of the while cycle, lb + 0.001 < ub can not be used 0.01 , because mid the calculation of the mean value calculation, for the double type of value otherwise there will be a large error.

three or two points searched for whileEnd Condition Determination

For integral types we usually use lb + 1 < ub , but for double the type of data there will be some loss of precision, so that the end condition is not so OK. The method used in the above question is the accuracy of the title in addition to 10. But sometimes this precision may not be enough, if the end condition lb + EPS < ub used in the EPS over the hour double data accuracy may not be enough to lead to the production of a dead loop ! At this time we will while for (int i = 0; i < 100; i++) Replace the loop body, 100 cycles can reach 10?3010^{-30}10?30 accuracy range , generally no problem.

Binary Searches-binary search

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.