【整数二分】Acwing789.数的范围
作者:互联网
Acwing789.数的范围
题解
最左边界,每次 mid >= x 则 r = mid, 再找左边是否有符合要求的边界。
最右边界,每次 mid <= x 则 l = mid, 再找右边是否有符合要求的边界。(注意当l = r-1时 ,(l+r)>> 1 == l 故我们需要 mid = (l + r)>> 1 + 1 )
写法一:多加一个else(易懂)
#include <iostream>
#include <cstdio>
using namespace std;
int arr[100002];
int n,q;
int k;
int find_left()
{
int mid, bg = 0, ed = n-1;
int res = -1;
while(bg <= ed){
mid = (bg+ed)/2;
if(arr[mid] < k)
bg = mid+1;
else if(arr[mid] > k)
ed = mid-1;
else
res = mid,ed = mid-1;
}
return res;
}
int find_right()
{
int mid,bg = 0, ed = n-1;
int res = -1;
while(bg <= ed)
{
mid = (bg+ed)/2;
if(arr[mid] < k)
bg = mid+1;
else if(arr[mid] > k)
ed = mid-1;
else
res = mid,bg = mid+1;
}
return res;
}
int main()
{
scanf("%d%d",&n,&q);
for(int i = 0; i < n; ++i)
scanf("%d",&arr[i]);
while(q--){
scanf("%d",&k);
printf("%d %d\n",find_left(),find_right());
}
return 0;
}
写法二:简略
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 100010;
int a[N];
int binary_left(int l, int r, int k)
{
int mid;
while( l < r)
{
mid = l + r >> 1;
if(a[mid] >= k) r = mid;
else l = mid + 1;
}
return l;
}
int binary_right(int l, int r, int k)
{
int mid;
while( l < r )
{
mid = (l + r >> 1) + 1;
if(a[mid] <= k) l = mid;
else r = mid - 1;
}
return l;
}
int main()
{
int n, q;
scanf("%d%d",&n, &q);
for(int i = 0; i < n; ++i)
scanf("%d",&a[i]);
int k, l, r;
while(q--)
{
scanf("%d",&k);
l = binary_left(0, n-1, k);
r = binary_right(0, n-1, k);
if(a[l] != k)
printf("-1 -1\n");
else
printf("%d %d\n",l,r);
}
return 0;
}
标签:二分,bg,int,res,mid,整数,while,Acwing789,ed 来源: https://www.cnblogs.com/czy-algorithm/p/16243924.html