问题
问题描述
现有N个大理石,每个大理石上写了一个非负整数、首先把各数从小到大排序;然后回答Q个问题。每个问题问是否有一个大理石写着某个整数x,如果是,还要回答哪个大理石上写着x。排序后的大理石从左到右编号为1~N。
输入大理石数量和需要回答问题数量,然后输入大理石上的每个非负整数,接着输入x
样例输入:
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
分析:要用到排序,还有查找。用lower_bound查找正好返回地址。lower_bound返回的是序列中第一个大于或等于查找值的的地址,用获得地址减去数组地址就是偏移量,即为第几号元素,再看该元素是否等于查找值就可以了。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n,q,a[10000],x;
int kase = 0;
while(cin>>n>>q&&n)
{
cout<<"CASE# "<<++kase<<endl;
for(int i = 0;i < n; i++)
{
cin>>a[i];
}
sort(a,a+n);
while(q--){
cin>>x;
int p = lower_bound(a,a+n,x)-a;
//在已知排序数组a中寻找x,lower_bound返回的是地址
//再减去数组a的地址为元素在数组中的位数
if(a[p] == x) cout<<x<<" found at "<<p+1<<endl;/*判断该元素是否为查找值
因为lower_bound可能返回的是大于该值的地址*/
else cout<<x<<" not found "<<"\n";
}
}
return 0;
}