C++的STL进一步总结之lower_bound和upper_bound
来源:互联网 发布:abc谋杀案知乎 编辑:程序博客网 时间:2024/05/16 19:05
一、lower_bound
用法:int t=lower_bound(a+l,a+r,m)-a
解释:在升序排列的a数组内二分查找[l,r)区间内的值为m的元素。返回m在数组中的下标。
特殊情况:
1.如果m在区间中没有出现过,那么返回第一个比m大的数的下标。
2.如果m比所有区间内的数都大,那么返回r。这个时候会越界,小心。
3.如果区间内有多个相同的m,返回第一个m的下标。
时间复杂度:
一次查询O(log n),n为数组长度。
实际上对长度为1000000的数组来1000000次lower_bound,学校渣电脑1.5-1.6s
自己手写的二分在1.2-1.4s左右
也不是很慢。
然后注意:m可以是pair等等。还有下标从0开始还是从1开始。
下面给出代码
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int a[1000010],t,n,l,r;int main(){//freopen("data.in","r",stdin);//freopen("data.out","w",stdout);scanf("%d",&t);for(int i=0;i<t;++i)scanf("%d",&a[i]);for(int i=0;i<t;++i){scanf("%d%d%d",&l,&r,&n);//在[l,r)区间内查找nprintf("%d\n",lower_bound(a+l,a+r,n)-a);}}
二、upper_bound
用法:int t=upper_bound(a+l,a+r,m)-a
解释:在升序排列的a数组内二分查找[l,r)区间内的值为m的元素。返回m在数组中的下标+1。
特殊情况:
1.如果m在区间中没有出现过,那么返回第一个比m大的数的下标。
2.如果m比所有区间内的数都大,那么返回r。这个时候会越界,小心。
3.如果区间内有多个相同的m,返回最后一个m的下标+1。
时间复杂度:
一次查询O(log n),n为数组长度。
实际上对长度为1000000的数组来1000000次upper_bound,学校渣电脑1.5-1.6s
自己手写的二分在1.2-1.4s左右
也不是很慢。
然后注意:m可以是pair等等。还有下标从0开始还是从1开始。
下面给出代码
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int a[1000010],t,n,l,r;int main(){//freopen("data.in","r",stdin);//freopen("data.out","w",stdout);scanf("%d",&t);for(int i=0;i<t;++i)scanf("%d",&a[i]);for(int i=0;i<t;++i){scanf("%d%d%d",&l,&r,&n);<span style="font-family: Arial, Helvetica, sans-serif;">//在[l,r)区间内查找n</span>printf("%d\n",upper_bound(a+l,a+r,n)-a);}}
0 0
- C++的STL进一步总结之lower_bound和upper_bound
- stl lower_bound 和 upper_bound
- STL lower_bound和upper_bound
- [STL] lower_bound和upper_bound
- C++ STL之lower_bound和upper_bound
- STL的lower_bound和upper_bound源码
- [C++] upper_bound和lower_bound
- STL之lower_bound()、upper_bound()、binary_search
- STL函数之lower_bound upper_bound
- C++ STL lower_bound 和 upper_bound
- STL中的lower_bound() 和 upper_bound()
- stl中的upper_bound和lower_bound
- STL----lower_bound和upper_bound算法
- stl lower_bound,upper_bound的实现;
- C/C++-STL中lower_bound与upper_bound的用法
- 【STL】STL之lower_bound与upper_bound
- STL algorithm之count、find、binary_search、lower_bound、upper_bound和equal_range的区别
- STL algorithm之count、find、binary_search、lower_bound、upper_bound和equal_range的区别
- 理解Fragment生命周期
- 关于字符串常考函数
- chrome启动失败
- android listview中getView重复被调用的问题
- java_map集合
- C++的STL进一步总结之lower_bound和upper_bound
- 凌夕卡密微商城
- hdu 2870 Largest Submatrix 最大子矩阵
- hdu 5441
- CVS介绍
- OpenGL 第二课
- Android0914<十八>(()Android网络连接HttpConnection、Volley,xUtils)(待更ing)
- Android DbUtils之查询数据库
- PL/SQL Developer配置使用说明