题解 | #牛可乐和魔法封印#
牛可乐和魔法封印
https://ac.nowcoder.com/acm/problem/235558
居然没人写题解,就让我来勇闯无人区!
这个题目好像就类似于高中的VB题,上代码
int findlowerbound(int target, int numsize) {
int l = 0;
int r = numsize - 1;
while (l <= r)
{
int m = (l + r) / 2;
if (num[m] < target)
{
l = m + 1;
}
else {
r = m - 1;
}
}
return l;
}
我们高中的时候好像是用i代替l,j代替r,然后用一个叫做key的变量代替target(死去的记忆开始攻击我)
总之完整的代码是这样的
#include<iostream>
using namespace std;
#define MAXN 100010
int _;
int num[MAXN];
int findlowerbound(int target, int numsize) {
int l = 0;
int r = numsize - 1;
while (l <= r)
{
int m = (l + r) / 2;
if (num[m] < target)
{
l = m + 1;
}
else {
r = m - 1;
}
}
return l;
}
int findUpperbound(int target, int numsize) {
int l = 0;
int r = numsize - 1;
while (l <= r)
{
int m = (l + r) / 2;
if (num[m] <= target)
{
l = m + 1;
}
else {
r = m - 1;
}
}
return r;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int _;
cin >> _;
for (int i = 0;i < _;i++) {
cin >> num[i];
}
int n;
cin >> n;
for (int i = 0;i < n;i++) {
int lowertarget, hightarget;
cin >> lowertarget >> hightarget;
int result = findUpperbound(hightarget, _) - findlowerbound(lowertarget, _) + 1;
cout << result << endl;
}
}