现有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 foundfound at 3
分析:
根据题目意思,我们首先应该先进行排序,再查找,然后我们可以使用algorithm头文件中的sort进行排序和lower_bound进行查找
#include <iostream>
#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;//lower_bound的作用是查找大于或等于x的第一个位置
if(a[p]==x)
{
printf("%d found at %d\n",x,p+1);
}
else
{
printf("%d not found\n",x);
}
}
}
return 0;
}
注:sort可对任意对象进行排序,不一定是内置类型。
排序对象可在普通数组里,也可以在vector中。前者用sort(a,a+n)的方式调用,后者用sort(v.begin(),v.end())的方式调用。