二分模板
作者:
自由基
,
2021-07-29 14:07:04
,
所有人可见
,
阅读 291
整数二分
将区间分为 [l,mid] , [mid+1, r] (左边界)
int bsearch( int l, int r ) {
while ( l < r ) {
int mid = l + r >> 1;
if ( check(mid)) r = mid;
else l = mid+1;
}
return l;
}
将区间分为 [l, mid-1], [mid, r] (右边界)
int bsearch( int l, int r ) {
while ( l < r ) {
int mid = l + r + 1 >> 1;
if ( check(mid)) l = mid;
else r = mid - 1;
}
return l;
}
浮点数二分
const double eps = 1e-8;
double bsearch( double l, double r ) {
while ( r - l > eps) {
double mid = ( l + r ) / 2;
if ( check(mid)) r = mid;
else l = mid;
}
return l;
}
算法第四版实现:
int bsearch( int l, int r ) {
while( l < r ) {
int mid = l + ( r - l ) / 2;
if( check(mid)) r = mid - 1;
else l = mid + 1;
}
return l;
}