Divide and conquer (2) - study notes for the rule of thirds

When the answer is divisible , we can solve it with a dichotomous answer . However, if the maximum value of a convex or concave function is required, the bisection is useless, and then we can use the rule of thirds to find the answer. 

A convex sequence/concave sequence is a popular saying that the left side of the maximum/minimum value of the sequence satisfies the loose monotone increase/decrease, and the right side satisfies the loose monotone decrease/increase. For example , 1, 2, 3, 6, 4 is a convex sequence, while 5, 4, 4, 3, 1, 2, 4, 6 is a concave sequence (see the figure below), and 6 and 1 in the figure are the maximum values ​​of the two sequences, respectively.


Similar to the dichotomy, the trichotomy also first takes the middle value (denoted as midl) of the lower bound (denoted as l) and the upper bound (denoted as r), and then takes the middle value of midl and r (denoted as midr) . Next, we want to compare which element of midl and midr is closer to the most value, and update the upper and lower bounds accordingly. Repeat the above operations until l>=r, then l at this time is the answer.

The code obtained after the specific implementation is as follows:

// Here is an example of finding elements in a convex sequence
int find(int l,int r,int v)//l stores the upper bound, r stores the lower bound, and v is the target element
{
    if(l>=r) return l;//Return the answer
    int midl=(l+r)>>1,midr=(midl+r)>>1;
    //Compare the size of midl and midr
    if(sum[midl]>sum[midr]) find(l,midr);//If midl is greater than midr, the maximum value is in the left interval
    else find(midl,r);//On the contrary, the maximum value is in the right interval
}



Note: If you have learned the rule of thirds through this article, please like and leave. Of course, you are also welcome to point out the shortcomings of this article in the discussion area. The author will correct this article in time
. Copyright statement: Please indicate the address for reprinting

Guess you like

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