输入一个整数n和n个整数,保证这n个整数已经按照从小到大进行排序。
然后输入一个整数q(q <= 100000)代表q次查询。接下来q行,每行含有一个整数m,代表一次查询。对于每次查询,使用二分查找判断m是否在之前输入的n个整数中出现过。如果出现,输出一行"Yes",否则输出"No"。
输入
第一行:一个整数n(n <= 100000)。
接下来n行,每行一个整数ai(1 <= ai <= 10^9)。
接下来一行,一个整数q。
接下来q行,每行输入一个整数x(1 <= x <= 10^9)。
输出
q行字符串,每行为"Yes"或"No"。
输入样例
5
1
3
4
5
7
3
4
5
0
输出样例
Yes
Yes
No
题解:
这题不解释了,直接手写一个二分即可,不过其实还可以用c/c++内置的函数
lower_bound()
来求。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
int n; int a[MAX];
int q,x;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while(cin >> n)
{
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
cin >> q;
for(int i = 1; i <= q; i++)
{
cin >> x;
/* 方法1
int l = 0;
int r = n-1;
while(l <= r)
{
int mid = (l+r)/2;
if(a[mid] == x)
{
break;
}
else if(a[mid] > x)
{
r = mid - 1;
}
else if(a[mid] < x)
{
l = mid + 1;
}
}
if(l <= r)
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
}
*/
/* 方法2
// 函数lower_bound()可以返回a数组中<=x的第一个数的位置
int * p = lower_bound(a,a+n,x);
if(*p == x)
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
}
*/
}
}
return 0;
}