CF:706B. Interesting drink (二分查找)
题意:不同奶茶店里同样的奶茶价格不同,问在当天Yuki持有的零钱能在几家店购买
思路:对价格数组排序,先优先判断是否会比较最大值和最小值,然后二分查找
#include<bits/stdc++.h>
using namespace std;
int main() {
int n, q, m, a[100005];
cin >> n; for (int i = 1; i <= n; ++i)cin >> a[i];
sort(a + 1, a + 1 + n);//可以改用qsort,效率更高点
cin >> q;
while (q--) {
cin >> m;
//比较最大最小值
if (m < a[1])cout << 0 << endl;
else if (m >= a[n])cout << n << endl;
else {
int left = 1, right = n;
int mid, ans;
while (left <= right) {
mid = (left + right) / 2;
if (a[mid] <= m) {
ans = mid;
left = mid + 1;
}
else right = mid - 1;
}
cout << ans << endl;
}
}
}