大理石在哪儿
现有N个大理石,每个大理石上写了一个非负整数、首先把各数从小到大排序然后回答Q个问题。每个问题问是否有一个大理石写着某个整数x,如果是,还要回答哪个大理石上写着x。排序后的大理石从左到右编号为1~N。
输入
4 1
2 3 5 1
5
5 2
1 3 3 3 1
2 3
样例输出:
CASE# 1:
5 found at 4
CASE# 2:
2 not found
3 found at 3
————————————————
版权声明:本文为CSDN博主「热爱学习的小羽呀」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/myCsdn_Xm/article/details/81252030
#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)
{
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
sort(a,a+n);//先排好序
while(q--)
{
scanf("%d",&x);
printf("CASE# %d:\n",++kase);
int p=lower_bound(a,a+n,x)-a;//在已排序的数组中寻找x,减去a也就是a[0]的地址就得到x的在数组a中的下标
if(a[p]==x)
{
printf("%d found at %d\n",x,p+1);//p+1是因为每个数字规定的排序是从1开始的
}
else
{
printf("%d not found \n",x);
}
}
}
return 0;
}
lower_bound( )和upper_bound( )都是利用二分查找的方法在一个排好序的数组中进行查找的。
在从小到大的排序数组中:
lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,
不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,
//不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。