UVa10474 Where is the Marble?(排序sort)

今天开始学STL,这是书上的一道例题,主要是用了sort函数和lower_bound函数,挺容易理解的。

lower_bound的作用是查找“大于或等于x的第一个位置”。

需要注意的是,不要忘记algorithm头文件。

使用STL真的方便了不少啊!

Where is the Marble?,UVa 10474

#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){
        printf("CASE# %d:\n",++kase);
        for(int i=0;i<n;i++) scanf("%d",&a[i]);
        sort(a,a+n);//排序
        while(q--){
            scanf("%d",&x);
            int p=lower_bound(a,a+n,x)-a;//在已排序数组a中寻找x 
            if(a[p]==x) printf("%d found at %d\n",x,p+1);
            else printf("%d not found\n",x);
        } 
    }
    return 0;
} 

 

posted @ 2017-02-08 20:17  wtzhang  阅读(113)  评论(0编辑  收藏  举报