题意:
蒜头君手上有个长度为
n
n
n 的数组
A
A
A。由于数组实在太大了,所以蒜头君也不知道数组里面有什么数字,所以蒜头君会经常询问在数组
A
A
A 中,比
x
x
x 大的最小值是多大?但是这次蒜头君要求这个数字必须大于
x
x
x,不能等于
x
x
x。
限制条件
1 <= n,m <= 100,000
0 <=
x
x
x <= 1,000,000
思路
二分查找。给数组
A
A
A 排序,然后利用upper_bound函数在数组中查询大于给定数的第一个数的下标,若下标等于
n
n
n 说明给定的数大于数组中的所有元素,无满足条件的数,因此输出 -1,其他情况就是有满足条件的数,直接输出查询出的下标对应的数即可。(本题对比T1561 二分查找(二)仅仅将lower_bound改为upper_bound)
AC代码如下:
#include "bits/stdc++.h"
using namespace std;
const int N = 1e5 + 10;
int a[N];
int main () {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
sort(a, a + n);
while (m--) {
int num;
cin >> num;
int idx = upper_bound(a, a + n, num) - a;
if (idx == n) cout << "-1\n";
else cout << a[idx] << "\n";
}
return 0;
}