Some Empirical Rules for Binary Search on the Answer Problems

Last updated on February 2, 2025 pm

This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.

Basic Idea

Divide a sequence into a blue region on the left and a red region on the right,

then we have the following basic code

代码CPP · 18 行
int search(int left,int right){
	int mid;
	while(left+1!=right){
		mid=left+(right-left>>1);
		if(isBlue(mid)) left=mid; // if(isRed(mid)) right=mid;
		else right=mid; //left=mid;
	}
	return left; //return right;
	/*
	if(check(right)) return right;
	else return left;
	*/

	/*
	if(check(;eft)) return left;
	else return right;
	*/
}

Below we will analyze the differences one by one.

Problems of Finding the Maximum of the Minimum

In this case, we need to write the isBlue() function, and the loop body is as follows

while(left+1!=right){
    mid=left+(right-left>>1);
    if(isBlue(mid)) left=mid; 
    else right=mid; 
}

Note that the inequality returned by isBlue() at the end should include equality, so that the answer is included within the blue boundary.

Then finally return left.

However, if it doesn't get AC, it may be due to boundary condition issues.

We need to write the return value like this:

if(isBlue(right)) return right;
else return left;

This ensures that the output is the largest possible answer.

Problems of Finding the Minimum of the Maximum

In this case, we need to write the isRed() function, and the loop body is as follows

while(left+1!=right){
    mid=left+(right-left>>1);
    if(isRedmid)) right=mid; 
    else left=mid; 
}

Note that the inequality returned by isRed() at the end should include equality, so that the answer is included within the red boundary.

Then finally return right.

However, if it doesn't get AC, it may be due to boundary condition issues.

We need to write the return value like this:

if(isRed(left)) return left;
else return right;

This ensures that the output is the smallest possible answer.


Some Empirical Rules for Binary Search on the Answer Problems
https://blog.wendain.ing/en/posts/binary-search-on-answer-experience/
Author
wendaining
Posted on
February 1, 2025
Updated on
February 2, 2025
Licensed under