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.

46 lines
1.2 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
int n, m;
// 前提q是一个有序递增的数组,当容器中的元素按照递增的顺序存储时
int q[8] = {1, 2, 3, 3, 3, 4, 5, 7};
//手写二分模板
int lower_bound(int l, int r, int x) {
while (l < r) {
int mid = (l + r) >> 1;
if (q[mid] >= x)
r = mid;
else
l = mid + 1;
}
return l;
}
int upper_bound(int l, int r, int x) {
while (l < r) {
int mid = (l + r) >> 1;
if (q[mid] > x)
r = mid;
else
l = mid + 1;
}
return l;
}
int main() {
/*
lower_bound
upper_bound
*/
int x = 4;
printf("%lld\n", lower_bound(q, q + 8, x) - q); //大于等于x的第一个位置
printf("%lld\n", upper_bound(q, q + 8, x) - q); //大于x的第一个位置
printf("%d\n", lower_bound(0, 8, x)); //大于等于x的第一个位置
printf("%d\n", upper_bound(0, 8, x)); //大于x的第一个位置
return 0;
}