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

二分法细节

时间:2014-07-18 14:29:37      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:style   io   re   c   c++   new   

#include<stdio.h>

int num[]={3,5,7,9,10,10,10,12,15,20,25,30};//10个数

int lower_bound(int *A,int L,int R,int V)

{

    int m;

    while(L<R)

    {

        m=L+(R-L)/2;

        if(A[m]>=V) R=m;//所求点在中点以左

        else L=m+1;//所求点在中点以右

    }

    return L;

}

int upper_bound(int *A,int L,int R,int V)

{

    int m;

    while(L<R)

    {

     m=L+(R-L)/2;

     if(A[m]<=V) L=m+1;//在中点以右

     else R=m;//在中点以左

    }

    return L;

}

int main()

{

    int num1;

    int n=10;

    while(n--)

    {

      scanf("%d",&num1);

      int l=lower_bound(num,0,11,num1);

      int r=upper_bound(num,0,11,num1);

      if(num[l]==num1&&num[r]==num1)  printf("yes\n");

      else printf("%d  %d\n",num[l],num[r]);

    }

    return 0;

}

总结:1.本题目中的upper_bound函数中的L=m+1;语句使得(如果V存在于数组中)最后返回值的比v所在坐标值大1(体现v出现的最大位置);

2.本题目的lower_bound函数是确定v在数组中出现的最小位置(如果存在的话);

3.本题目中v如果在数组中有多个则在区间[lower_bound,upper_bound)(左闭右开)

4.如果不能在该值的话:则upper_bound等于lower_bound,区间为空;

5.upper_boundlower_bound函数本身就是c++的库函数。

二分法细节,布布扣,bubuko.com

二分法细节

标签:style   io   re   c   c++   new   

原文地址:http://www.cnblogs.com/khbcsu/p/3852701.html

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