九度OJ 1173:查找

题目描述:

输入数组长度 n 
输入数组      a[1...n] 
输入查找个数m 
输入查找数字b[1...m] 
 
输出 YES or NO  查找有则YES 否则NO 。

输入:

输入有多组数据。
每组输入n,然后输入n个整数,再输入m,然后再输入m个整数(1<=m<=n<=100)。

输出:

如果在n个数组中输出YES否则输出NO。

样例输入:
5
1 5 2 4 3
3
2 5 6
样例输出:
YES
YES
NO
来源:
2010年北京邮电大学网院研究生机试真题
#include <cstdio>
#include <algorithm>
using namespace std;
bool binarySearch(int x[102],int n,int q){
    int s = 0;
    int t = n-1;
    while(s <= t){
        int mid = (s+t)/2;
        if(x[mid] == q)return true;
        if(x[mid] < q)s = mid + 1;
        else t = mid - 1;
    }
    return false;
}
int main(){
    int n,m;
    int x[102];
    while(scanf("%d",&n) != EOF){
        for(int i = 0;i < n;i++)
            scanf("%d",&x[i]);
        sort(x,x+n);
        scanf("%d",&m);
        int s;
        for(int j = 0;j < m;j++){
            scanf("%d",&s);
            printf("%s
",binarySearch(x,n,s) == true ? "YES" : "NO");
        }
    }
}
原文地址:https://www.cnblogs.com/starryxsky/p/7095479.html