码迷,mamicode.com
首页 > 其他好文 > 详细

二分查找

时间:2018-08-31 17:10:41      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:else   ...   函数   区间   bool   turn   二分   int   条件   

区间[a,b],[a,c]满足条件而(c,b]不满足条件,或者,[a,c)不满足条件而[c,b]满足条件。函数bs(a,b)返回c。
特判:

  • [a,b]都不满足条件,bs(a,b)返回-1
  • [a,b]都满足条件,bs(a,b)返回b
bool ok(int m)
{
    //...
}
int bs(int l,int r)
{
    int m;
    if(ok(l)&&ok(r))return r;
    if(!ok(l)&&!ok(r))return -1;
    if(!ok(l)){r=r^l;l=r^l;r=r^l;}
    while(r-l>1||l-r>1)
    {
        m=(l+r)/2;
        if(ok(m))l=m;
        else r=m;
    }
    return l;
}

二分查找

标签:else   ...   函数   区间   bool   turn   二分   int   条件   

原文地址:https://www.cnblogs.com/maoruimas/p/9566244.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!