If there is monotonicity, it must be dichotomized, and if there is no monotonicity, it can also be dichotomized
Integer binary steps:
1. Find an interval [L, R], so that the answer must be in the interval
2. Find a judgment condition that makes the judgment condition have a duality, and the answer must be the dividing point of the duality
3. Analyze whether the midpoint M is established under the judgment condition. If it is established, consider which interval the answer is in. If it is not established, consider which interval the answer is in.
4. If the update method writes R=Mid, no processing is required; if the update method writes L=Mid, you need to add 1 when calculating Mid
The first type of dichotomous template:
ans is the right endpoint of the green area
Divide [L, R] into [L, M-1], [M, R]
if M is green, it means that ans is still in [M,R]
else indicates that ans is in [L, M-1]
Analyze limit cases:
L=R-1
M=(L+R+1)/2=R
R=M-1=R-1=L
Core code:
while(L<R){
int mid=(L+R+1)/2;
if(mid为绿) L=mid;
else R=mid-1;
}
How to judge whether it is the first type of template:
If L=M, it means that +1 is needed when taking the midpoint, that is, (L+R+1)/2
The second type of dichotomous template:
ans is the left endpoint of the blue area
Divide [L, R] into [L, M], [M+1, R]
If M is blue, it means that ans is in [L,M]
else indicates that ans is in [M+1, R]
Analyze limit cases:
L=R-1
M=(L+R)/2=L
L=M+1=L+1=R
Core code:
while(L<R){
int mid=(L+R)/2;
if(mid为蓝) R=mid;
else L=mid+1;
}
How to judge whether it is the first type of template:
If R=M, it means that there is no need to +1 when taking the midpoint, that is, (L+R)/2
Real dichotomy:
Real binary template:
Divide the interval [L, R] into [L, M], [M, R]
if ans is sitting in the left interval [M, R], L=M
else if ans is in the right interval [L, M] R=M
while(L-R>1e-6){
double mid=(L+R)/2;
if(mid为左区间) R=mid;
else L=mid;
}