二分
作者:
温婉和熊熊
,
2020-04-12 12:36:29
,
所有人可见
,
阅读 507
#include <iostream>
#include <algorithm>
using namespace std;
int a[10] = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5};
int main()
{
int x;
cin >> x;
// lower_bound 返回第一个大于等于x的下标
int l = 0, r = 9;
while (l < r)
{
int mid = l + r >> 1;
if (a[mid] >= x) r = mid;
else l = mid + 1;
}
cout << l << endl;
// upper_bound 返回第一个大于x的下标
l = 0, r = 9;
while (l < r)
{
int mid = l + r >> 1;
if (a[mid] > x) r = mid;
else l = mid + 1;
}
cout << l << endl;
// lower_bound 返回第一个小于等于x的下标
l = 0, r = 9;
while (l < r)
{
int mid = l + r + 1 >> 1;
if (a[mid] <= x) l = mid;
else r = mid - 1;
}
cout << l << endl;
// upper_bound 返回第一个小于x的下标
l = 0, r = 9;
while (l < r)
{
int mid = l + r + 1 >> 1;
if (a[mid] < x) l = mid;
else r = mid - 1;
}
cout << l << endl;
return 0;
}