简单说一下C++中的lower_bound函数跟upper_bound函数这是algorihm头文件下的查找函数通过二分查找lower函数查找的是大于等于x的第一个位置,而upper查找的是大于x的第一个位置格式如下 lower_bound(数组名,数组名+数组内元素个数,想要查找的元素x)- 数组名upper函数格式相同贴一下刘汝佳的算法竞赛入门经典(第二版)p109代码
#include
#include
#include
using namespace std;
const int maxn = 10000;
int main()
{
int n,q,x,a[maxn],kase = 0;
while(scanf("%d%d",&n,&q)==2&&n)
{
printf("case# %d\n",++kase);
for(int i = 0; i < n; ++i)
{
scanf("%d",&a[i]);
}
sort (a , a + n);
while(q--)
{
scanf("%d",&x);
int p = lower_bound(a,a+n,x) - a;//在以排序数组中查找x
if(a[p] == x)printf("%d found at %d\n",x,p+1);
else printf("%d not found\n",x);
}
}
return 0;