问题描述
现有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
#include<iostream>
#include<algorithm>
const int maxn=10000;
using namespace std;
int main()
{
int n,q,x,a[maxn],Case=0;//n代表大理石数目,q代表问题数目,x为待查找数
while(scanf("%d%d",&n,&q)==2&&n&&q)
{
printf("CASE %d:",++Case);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
while(q--)
{
cin>>x;
int p=lower_bound(a,a+n,x)-a;
if(a[p]==x)cout<<x<<" found at "<<p+1<<endl;
else cout<<x<<" not found"<<endl;
}
}
return 0;
}
Tips:
sort函数:将数组a从小到大排序 sort(a,a+n).
lower_bound(a,a+n,x)
寻找数组a中x的大小,采用折半查找速度超快0.0.