#include<cstdio>
#include<algorithm>
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;
if(a[p]==x)printf("%d found at %d\n",x,p+1);
else printf("%d not found\n",x);
}
}
return 0;
}
这个题里面有一个stl函数 lower_bound,这个函数参数为(数组起始位置,数组终止位置,所需要寻找的数x)—数组名,
函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置
举例如下:
一个数组number序列为:4,10,11,30,69,70,96,100.设要插入数字3,9,111.pos为要插入的位置的下标
则
pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number数组的下标为0的位置。
pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number数组的下标为1的位置(即10所在的位置)。
pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number数组的下标为8的位置(但下标上限为7,所以返回最后一个元素的下一个元素)。
所以,要记住:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!~
返回查找元素的第一个可安插位置,也就是“元素值>=查找值”的第一个元素的位置