这个题的要求是先排序,后查找。然后书上是用了 sort 和 lower_bound函数都在algorithm头文件里
sort函数是一个模板函数,可以对任意对象进行排序,不一定是内置类型。还可以改变其排序规则。
lower_bound():查找大于或者等于x的第一个位置。
upper_bound(): 查找大于x的第一个位置
比如数组为 a[5]=1,2,3,3,3
然后查找0,1,3
int p=lower_bound(a,a+5,0)-a;//p=0
int p=upper_bound(a,a+5,0)-a;// p=0
int p=lower_bound(a,a+5,1)-a;//p=0;
int p=upper_bound(a,a+5,1)-a;//p=1;
int p=lower_bound(a,a+5,3)-a;//p=2;
int p=upper_bound(a,a+5,3)-a;//p=5;
然后就是这道题的代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
const int maxn=10000;
int a[maxn];
int main()
{
int n,m,case1=0;
while(scanf("%d %d",&n,&m)!=EOF&&n+m)
{
memset(a,0,sizeof(a));
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
printf("CASE# %d:\n",++case1);
for(int i=0;i<m;i++){
int q;
scanf("%d",&q);
int p=lower_bound(a,a+n,q)-a;
if(a[p]==q) printf("%d found at %d\n",q,p+1);
else printf("%d not found\n",q);
}
}
return 0;
}