(stl排序+检索)大理石在哪

问题:

现有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 found
3 found at 3

分析与解答

1.利用sort排序
2.利用lower_bound(a,a+n,x)
在a[0]到a[n-1]中找大于等于x的第一个位置
注意返回的是个指针,如果求第几个元素,需要减去a[0]

#include<iostream>
#include<cstdio> 
#include<algorithm>
using namespace std;
const int maxn=10000;

int main(){
    int n,q,k=0;
    while(cin>>n>>q&&n){
        k++;
        cout<<"CASE# "<<k<<endl;
        int a[maxn];
        for(int i=0;i<n;++i){
            cin>>a[i];
        }
        sort(a,a+n);
        while(q--){
            int b;
            cin>>b;
            int p=lower_bound(a,a+n,b)-a;//位置相减即为下标
            if(a[p]==b) cout<<b<<" found at "<<p+1<<endl;
            else cout<<b<<" not found"<<endl;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40828914/article/details/81109829
今日推荐