You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.0 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
int n, m;
const int N = 110;
/*
q,
*/
int q[N] = {1, 2, 3, 3, 3, 4, 5};
int l, r;
//二分算法之手动版本
int manual_lower_bound(int l, int r, int x) {
while (l < r) {
int mid = (l + r) / 2;
if (q[mid] >= x)
r = mid;
else
l = mid + 1;
}
return l;
}
int manual_upper_bound(int l, int r, int x) {
while (l < r) {
int mid = (l + r) / 2;
if (q[mid] > x)
r = mid;
else
l = mid + 1;
}
return l;
}
int main() {
/**********************************************************/
//方法1yxc 大法
//从0~6找出>=3的第一个位置
l = 0, r = 6;
int x = 3;
while (l < r) {
int mid = (l + r) >> 1;
if (q[mid] >= x)
r = mid;
else
l = mid + 1;
}
printf("%d\n", l);
//从0~6找出<=3的最后一个位置
l = 0, r = 6;
x = 3;
while (l < r) {
int mid = (l + r + 1) >> 1;
if (q[mid] <= x)
l = mid;
else
r = mid - 1;
}
printf("%d\n", l);
/*
2STL lower_bound,upper_bound
lower_bound
upper_bound
*/
printf("%lld\n", lower_bound(q, q + 7, x) - q);
printf("%lld\n", upper_bound(q, q + 7, x) - q - 1);
/**********************************************************/
/*
3 lower_bound,upper_bound
*/
printf("%d\n", manual_lower_bound(0, 7, x));
printf("%d\n", manual_upper_bound(0, 7, x) - 1);
/**********************************************************/
return 0;
}