UVa 10474 Where is the Marble? 【STL】【排序与检索-sort和lower_bound】

来源:互联网 发布:少女前线 妖精数据 编辑:程序博客网 时间:2024/06/05 04:27

题目链接:点击打开链接

题意:N个大理石,每个大理石上都有一个非负整数。首先按照从小到大顺序排序,然后回答Q个问题,每个问题会有一个正整数x,如果大理石上存在这个数x,则输出他的排好序后的位置,否则输出未找到x。

思路:输入完成后sort排序,然后用lower_bound找出第一个大于或等于x的位置,再判断这个位置上的数是否等于x。

AC代码:

#include <cstdio>#include <iostream>#include <cstring>#include <algorithm>#include <cmath>using namespace std;int a[10005];int main(){    int m, n, tem;    int cou = 0;    while(~scanf("%d%d",&m,&n))    {        if(m == 0 && n == 0) break;        memset(a,0,sizeof(a));        for(int i = 0; i < m; ++i)            scanf("%d",&a[i]);        printf("CASE# %d:\n",++cou);        sort(a, a+m);        while(n--)        {            scanf("%d",&tem);            int q = lower_bound(a, a+m, tem) - a; //在已排序的数组a中寻找x            if(a[q] == tem) cout << tem << " found at " << q + 1 << endl;            else cout << tem << " not found" << endl;        }    }    return 0;}

主要是为了练习lower_bound的用法,格式:  int tem = lower_bound(数组名, 数组名+查找范围, 查找的元素) - 数组名; 
0 0
原创粉丝点击