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

本文介绍了一种利用C++ STL中的lower_bound函数解决特定查找问题的方法。通过一个实例问题,详细展示了如何对一系列整数进行排序,并针对给定的目标值在排序后的数组中查找其位置或确认不存在。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:点击打开链接

题意: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(数组名, 数组名+查找范围, 查找的元素) - 数组名; 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值