二分回顾
2015-08-08 16:20
253 查看
lower = lower_bound(a,a+n,3); upper = upper_bound(a,a+n,3); for(int i=lower;i<upper;i++) cout<<a[I]<<' '; //output -*- 3 3 3
1.STL里面有upper_bound()以及lower_bound()
lower_bound(a,a+n,value);返回值为数组a中≥value的位置。如果都比value小,则指向a+n,注意该位置越界。
upper_bound(a,a+n,value);返回值为数组a中>value的位置。如果都比value小,则指向a+n,注意该位置越界。
## 这两个函数返回的是数组的迭代器,因此想得到index,需要减去数组原始坐标。
区别在于如果数组为
pos: 0 1 2 3 4 5 6 7
val: 1 2 3 3 3 6 7 8 ,lower查找3返回2,upper返回5,[lower,upper)构成value取值的区间
用法:
for( int i=0;i<20;i++) g[i]=i;
index = lower_bound(g,g+n,10) - g; /*此处得到3的位置*/
2.手写
经常题目里不会出现一个排序好的数组,而是一个函数,那么需要手写
为了标准化程序应该模拟lower_bound()和upper_bound()
lower_bound():
返回值为数组a中≥value的位置
while(x<y){ mid=x+(y-x)/2; if(Judge(mid)>=value) y=mid; else x=mid+1; } return x;
upper_bound():
返回值为数组a中>value的位置
while(x<y){ mid=x+(y-x)/2; if(Judge(mid)>value) y=mid; else x=mid+1; } return x;
二分的区间定为[x,y),即查找的区间。 但是返回值的候选区间是[x,y]。
因为mid取值为(x+y)/2的下界,所以mid不会等于y,[x,mid]不会与原区间[x,y]相同,不会死循环。
而[mid+1,y]与[x,y],mid+1>=x+1同样不会陷入死循环。
相关文章推荐
- 【Obective-C编程开发】Objective-C之BOOL一清二楚
- C语言中关于.h文件和.c文件详细解析
- C.Stripe(Codeforces Beta Round #18 (Div. 2 Only))
- 用户'sa'登录失败(DataGridView)
- MySQL连接查询
- 部分华为校园招聘机试试题及答案(C语言版本)
- 文件描述符及其重定向的学习笔记
- Input设备驱动之事件类型
- 设计模式--组合模式
- NSDatepicker
- iOS程序支持64位以及project.pbxproj文件的介绍
- socket长连接所用到的八大技术
- Thinkphp 3.2命名空间版如何使用PHPExcel导入Excel文件
- POJ3278.Catch That Cow
- 【POJ3270】【Cow Sorting】
- 利用jaxb进行xml与javabean的数据绑定
- Linux命令学习之二
- HDOJ 2087 剪花布条 (KMP简单题)
- 虚拟内存
- hdu1698