二分
一、整数
- 步骤
- 找中间值:
mid = (l + r) >> 1
mid = (l + r + 1) >> 1
- 三个要点
- 判断
mid
在哪一边,是否包含在内
mid
怎么取
- 两种
mid = (l + r) >> 1
(向下取整)
(l, mid)
(mid + 1, r)
mid = (l + r + 1) >> 1
(向下、上取整)
(l, mid - 1)
(mid, r)
//789 sh
#include <iostream>
using namespace std;
const int N = 100000;
int arr[N];
int main()
{
int n, q;
scanf("%d%d", &n, &q);
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int num, l, r;
for (int i = 0; i < q; i++)
{
scanf("%d", &num);
int l = 0, r = n - 1;
while (l < r)
{
int mid = l + r >> 1;
if (arr[mid] >= num)
{
r = mid;
}
else
{
l = mid + 1;
}
}
if (arr[l] != num) //即没有找到
{
cout << "-1 -1" << endl;
}
else
{
cout << l << " ";##
int l = 0, r = n - 1;
while (l < r)
{
int mid = l + r + 1 >> 1;
if (arr[mid] <= num)
{
l = mid;
}
else
{
r = mid - 1;
}
}
cout << l << endl;
}
}
return 0;
}
二、浮点数
//790 数的三次方根
#include <iostream>
using namespace std;
int main(){
double l = -10000, r = 10000;
double n;
cin >> n;
while(r - l > 1e-8){
double mid = (l + r) / 2;
if(mid * mid * mid < n){
l = mid;
}
else{
r = mid;
}
}
printf("%lf", l);
return 0;
}