二分查找1

版权声明:个人做题总结专用~ https://blog.csdn.net/tb_youth/article/details/84844978

zcmu:
1099: 查找元素II
Time Limit: 1 Sec Memory Limit: 128 MB

[Submit][Status][Web Board]
Description

给定一个整数集合s,集合中有n个元素,我有m次询问,对于每次询问给定一个整数x,若 x存在于集合s中输出x found at y,y为集合s按从小到大排序后第一次出现x的下标,否则输出x not found.

Input

多组测试数据,每组第一行为两个正整数n,m.(1<=n,m<=1000)代表集合中元素的个数和查询次数,接下来n行每行有一个正整数代表集合里的元素.(每个整数的大小小于等于100000),接下来 m行每行有一个正整数代表查询的元素.

Output

详见sample output

Sample Input

4 1
2
3
5
1
5
5 2
1
3
3
3
1
2
3

Sample Output

CASE# 1:
5 found at 4
CASE# 2:
2 not found
3 found at 3

HINT

Source
//好久前写的,现在拿出来当总结
Ac_code~:

#include<stdio.h>
#include<algorithm>
using namespace std;
int a[1005],b[1005];
int search2(int aim,int a[],int l)//二分法查找
{
    int top=0,tail=l-1,z,f=-1;
    while(top<=tail)
    {
        z=(tail+top)/2;
        if(aim<a[z])
        {
            tail=z-1;
        }
        else if(aim>a[z])
        {
            top=z+1;
        }
        else
        {
            f=z;
            break;
        }
    }
    return f;
}
int main()
{
    int n,m,k=0;
    while(~scanf("%d%d",&n,&m))
    {
        k++;
        int i,j,w;
        for(i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
        }
        sort(a,a+n);
        for(j=0; j<m; j++)
        {
            scanf("%d",&b[j]);
        }
        printf("CASE# %d:\n",k);
        for(i=0; i<m; i++)
        {
            w=search2(b[i],a,n);//查询到返回数组下标值,否知返回的为-1
            if(w==-1) printf("%d not found\n",b[i]);
            else
            {
                for(j=w-1; j>=0; j--)
                {
                    if(a[w]!=a[j]) break;
                    else w=j;
                }
                printf("%d found at %d\n",b[i],w+1);
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tb_youth/article/details/84844978
今日推荐