ZZULIOJ:1152: 二分搜索

题目描述

在有序序列中查找某一元素x。

输入

首先输入一个正整数n(n<=100000),表示该序列有n个整数,然后按从小到大的顺序输入n个整数;

接着是一个正整数m,表示有m次查找;

最后是m个整数,表示m个要查找的整数x。

输出

对于每一次查找,有一行输出。若序列中存在要查找的元素x,则输出元素x在序列中的序号(序号从0开始);若序列中不存在要查找的元素x,则输出"Not found!"。

样例输入 Copy

5
1 3 5 7 9 
11
-1
1
2
3
4
5
6
7
8
9
10

样例输出 Copy

Not found!
0
Not found!
1
Not found!
2
Not found!
3
Not found!
4
Not found!

源代码 

//本题为标准的二分法模板题
//查看ACM算法专栏中的《二分法》文章即可,不再赘述 
#include <iostream>
using namespace std;
const int N = 1000000 + 10;
int a[N];
int main()
{
    int n;
    cin >> n;
    for(int i = 0;i < n ;i ++ )cin >> a[i];
    int m;
    cin >> m;
    while(m -- )
    {
        int x;
        cin >> x;
        int l = 0,r = n - 1;
        while(l < r)
        {
            int mid = l + r >> 1;
            if(a[mid] >= x)r = mid;
            else l = mid + 1;
        }
        if(a[l] == x)cout << l << endl;
        else cout << "Not found!" << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/couchpotatoshy/article/details/126077274