UVA.10474 Where is the Marble ( 排序 二分查找 )

UVA.10474 Where is the Marble ( 排序 二分查找 )

题意分析

大水题一道。排序好找到第一个目标数字的位置,返回其下标即可。暴力可过,强行写了一发BS,发现错误百出。应了那句话:基础不牢,地动山摇。
记录一下自己BS的常见错误:

1.需要传入的参数是,搜索的区间[l,r]和搜索的目标值t;
2.一般被搜索的对象以全局变量的身份出现,故不需要传参进去;
3.退出循环的条件是l < r 注意这里可没有等号;
4.若t在mid左边或等于mid,要把右坐标r移动到m的位置,反之,要把l移动到mid+1的位置;
5.最后直接返回l即可,l即为找到的匹配位置,或者是最接近的位置。
6.这种写法还有改进的余地。

代码总览

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define nmax  10005
using namespace std;
int a[nmax];
bool cmp(int a, int b)
{
    return a<b;
}
int bs(int l, int r,int t)
{
    int m;
    while(l<r){
        m = (l+r)/2;
        if(t<=a[m]) r = m;
        else if(t>a[m])l = m+1;
    }
    return l;
}
int main()
{
    //reopen("in.txt","r",stdin);
    int n,m;
    int cas = 1;
    while(scanf("%d%d",&n,&m) &&n){
        printf("CASE# %d:
",cas++);
        for(int i =1; i<=n; ++i) scanf("%d",&a[i]);
        sort(a+1,a+1+n,cmp);
        for(int i = 1;i<=m;++i){
            int t;
            scanf("%d",&t);
            int ans =bs(1,n,t);
            if(a[ans] == t) printf("%d found at %d
",t,ans);
            else printf("%d not found
",t);
            //printf("%d
",bs(1,n,t,f));
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/pengwill/p/7367137.html