当前位置: 代码迷 >> 综合 >> C++ lower_bound 与 upper_bound函数
  详细解决方案

C++ lower_bound 与 upper_bound函数

热度:40   发布时间:2023-11-04 06:49:59.0

头文件:#include <algorithm>

时间复杂度:一次查询O(log n),n为数组长度。

图示:

lower_bound:

功能:查找非递减序列[first,last) 内第一个大于或等于某个元素的位置。

返回值:如果找到返回找到元素的地址否则返回last的地址。(这样不注意的话会越界,小心)

用法:int t=lower_bound(a+l,a+r,key)-a;(a是数组)。

upper_bound:

功能:查找非递减序列[first,last) 内第一个大于某个元素的位置。

返回值:如果找到返回找到元素的地址否则返回last的地址。(同样这样不注意的话会越界,小心)

用法:int t=upper_bound(a+l,a+r,key)-a;(a是数组)。

注意 调用之前必须确定序列为有序序列,否则调用出错。

相关题目 UVA - 10474

AC代码

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=10000;
int main()
{int a,b,s[maxn],key;key=0;while(scanf("%d%d",&a,&b)==2&&a){printf("CASE# %d:\n",++key);for(int i=0;i<a;i++)scanf("%d",&s[i]);sort(s,s+a);while(b--){int m;cin>>m;int p=lower_bound(s,s+a,m)-s;if(s[p]==m)printf("%d found at %d\n",m,p+1);elseprintf("%d not found\n",m);}}return 0;
}