二分查找及lower_bound与upper_bound
来源:互联网 发布:乐器吉他淘宝 编辑:程序博客网 时间:2024/05/17 07:31
二分查找(迭代实现)
二分查找#include <iostream>#include<cstdio>#include<cstring>#include<cmath>const int maxn=1000;int a[maxn],n,t[maxn],p;int bsearch(int *a,int x,int y,int n){ int m; while(x<y) { m=x+(y-x)/2; if(a[m]==n)return m; else if(a[m]>n)y=m; else x=m+1; } return -1;}int main(){ while(~scanf("%d",&n)) { for(int i=0;i<n;i++) scanf("%d",&a[i]); int v; scanf("%d",&v); int k=bsearch(a,0,n,v); printf("%d\n",k); }}
运用二分查找求下界(lower_bound)
#include <iostream>#include<cstdio>#include<cstring>#include<cmath>const int maxn=1000;int a[maxn],n,t[maxn],p;int lower_bound(int *a,int x,int y,int n){ int m; while(x<y) { m=x+(y-x)/2; if(a[m]>=n)y=m; else x=m+1; } return x;}int main(){ while(~scanf("%d",&n)) { for(int i=0;i<n;i++) scanf("%d",&a[i]); int v; scanf("%d",&v); int k=lower_bound(a,0,n,v); printf("%d\n",k); }}
相对的求上界(upper_bound)只需对上面代码稍作修改
#include <iostream>#include<cstdio>#include<cstring>#include<cmath>const int maxn=1000;int a[maxn],n,t[maxn],p;int lower_bound(int *a,int x,int y,int n){ int m; while(x<y) { m=x+(y-x)/2; if(a[m]<=n)x=m+1; else y=m; } return x;}int main(){ while(~scanf("%d",&n)) { for(int i=0;i<n;i++) scanf("%d",&a[i]); int v; scanf("%d",&v); int k=lower_bound(a,0,n,v); printf("%d\n",k); }}
注意:用上面两个函数可以求出一个数在序列中所在位置的二区间,但用lower_bound与upper_bound两个函数求出来的区间是[l,r)的半闭半开区间,不用误用为单纯的闭区间(为什么留给读者自己思考)
- 二分查找及lower_bound与upper_bound
- 二分查找,lower_bound,upper_bound
- 【lower_bound】【upper_bound】二分查找
- STL中的二分查找,lower_bound();与upper_bound();
- 二分查找和lower_bound & upper_bound
- STL 中 lower_bound 与 upper_bound 与 二分查找
- 二分查找与STL中的lower_bound(),upper_bound(),binary_search()
- 查找和二分查找 lower_bound upper_bound
- 二分查找—lower_bound 、upper_bound 、binary_search
- STL中的二分查找--lower_bound/upper_bound/binary_search
- STL之二分查找(binary_search(),lower_bound(),upper_bound() )
- STL之二分查找(binary_search(),lower_bound(),upper_bound() )
- STL之二分查找(binary_search(),lower_bound(),upper_bound() )
- STL之二分查找(binary_search(),lower_bound(),upper_bound() )
- STL 二分查找(binary_search(),lower_bound(),upper_bound() )
- STL 二分查找 upper_bound和lower_bound用法
- 二分lower_bound()与upper_bound()的运用
- C中的二分函数:upper_bound()与lower_bound()
- sql group by 子句
- linq日期转换
- java并发库之Executors常用的创建ExecutorService的几个方法说明
- smali语法
- Per-cpu 变量
- 二分查找及lower_bound与upper_bound
- HDU1271---整数对 HDU(100)
- 物料主税码及客户税码在哪个表里 ?
- Android_JellyBean 4.2.1 Camera Service 请求过程分析
- 运行程序提示access violation at address的解决方法
- flash模糊遮罩的实现
- tongji 30029 插头dp
- cloudfoundry vmc常用命令
- 自己的usaco代码---PROB Milking Cows