Where is the Marble? UVA - 10474

本文介绍了一个使用C++实现的二分查找算法案例,包括lower_bound和upper_bound函数的应用,通过一个暑假训练题目的形式展示了如何查找数组中特定元素的位置。代码实现了输入一组数据并对其进行排序,然后对指定的查询值进行查找,输出其位置或未找到的消息。

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

暑假训练 1

lower_bound(num,num+n,k)-num;返回在数组中大于等于k的第一个下标

upper_bound()返回大于的第一个下标

binary_search()二分查找是否存在

#include <iostream>
#include <algorithm>
#include <cstdio>

using namespace std;

bool cmp(int a,int b)
{
    return a>b;
}
int num[10000];
int main()
{
    int m,n;

    int cont=1;
    while(1)
    {
        scanf("%d%d",&n,&m);
        if(n==0&&m==0)
            break;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&num[i]);
        }
        sort(num,num+n);
        cout<<"CASE# "<<cont<<":"<<endl;
        cont++;
        for(int i=0;i<m;i++)
        {
            int k;
            scanf("%d",&k);
            binary_search()
            int k1=lower_bound(num,num+n,k)-num;

            if(num[k1]==k)
            {
                cout<<k<<" found at "<<k1+1<<endl;
            }
            else
                cout<<k<<" not found"<<endl;
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值