您的位置:首页 > 其它

Uva 10474 Where is the Marble?(排序与检索)

2017-02-12 11:45 232 查看
本题若掌握了sort()和lower_bound()两个函数,就无难点。

#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn=10005;

int main(){
int N,Q,kase=0;
while(scanf("%d%d",&N,&Q)==2&&N){
int marble[maxn];
int question[maxn];
for(int i=0;i<N;i++)scanf("%d",&marble[i]);
for(int i=0;i<Q;i++)scanf("%d",&question[i]);
sort(marble,marble+N);    //排序
printf("CASE# %d:\n",++kase);
for(int i=0;i<Q;i++){
int p=lower_bound(marble,marble+N,question[i])-marble; //在已排序的数组中寻找某个数
if(marble[p]==question[i]) printf("%d found at %d\n",question[i],p+1);
else printf("%d not found\n",question[i]);
}
}
return 0;
}


注意点:

1. sort():对于常规的数据类型默认从小到大排序 。对任意对象排序时,需要定义“小于”符号。

对数组中的元素进行排序:sort(a,a+n)

对vector中的元素进行排序:sort(v.begin(),v.end())

2.lower_bound()的返回值减去数组的地址就是要查找的元素在数组中的位置。

int p=lower_bound(marble,marble+N,question[i])-marble;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: