AcWing 789. 二分复习——数的范围
原题链接
简单
作者:
别期待太多
,
2024-09-30 16:32:38
,
所有人可见
,
阅读 1
#include<iostream>
#include<cstdio>
using namespace std;
const int N = 100010;
int n, q, k, a[N];
int main()
{
scanf("%d %d", &n, &q);
for(int i = 0; i<n; i++)
scanf("%d", &a[i]);
while(q--)
{
scanf("%d", &k);
//先寻找首次出现
int l = 0, r = n-1;
while(l < r)
{
int mid = l+r >> 1;
if(a[mid] >= k)
r = mid;
else
l = mid+1;
}
if(a[l] != k)
{
printf("-1 -1\n");
continue;
}
else
{
printf("%d ",l);
//接着找最后一次出现的
l = 0, r = n-1;
while(l < r)
{
int mid = l+r+1 >> 1;
if(a[mid] <= k)
l = mid;
else
r = mid-1;
}
printf("%d\n",l);
}
}
return 0;
}