bool check(int x) {/* ... */} // 查看 x 是否满足某种性质
// 区间 [l, r] 被划分成 [l, mid] 和[mid + 1, r]时应用:int bsearch_1(int l, int r) {while (l < r) {
int mid = l + r >> 1;
if (check(mid)) r = mid;
else l = mid + 1;
}
return l;
}
// 区间 [l, r] 被划分成 [l, mid - 1] 和[mid, r]时应用:int bsearch_2(int l, int r) {while (l < r) {
int mid = l + r + 1 >> 1;
if (check(mid)) l = mid;
else r = mid - 1;
}
return l;
}
bool check(double x) {/* ... */} // 查看 x 是否满足某种性质
double bsearch_3(double l, double r) {
const double eps = 1e-6; // eps 示意精度,取决于题目对精度的要求
while (r - l > eps) {double mid = (l + r) / 2;
if (check(mid)) r = mid;
else l = mid;
}
return l;
}