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.

39 lines
1.1 KiB

2 years ago
#include <bits/stdc++.h>
// 需要仔细研究一下lower_bound,upper_bound,还有手动二分的差别,这个细节很重要
// https://www.cnblogs.com/linsinan1995/p/13620590.html
using namespace std;
const int N = 110;
int a[9] = {1, 2, 2, 3, 3, 3, 4, 6, 7};
// 区间[l, r]被划分成[l, mid]和[mid + 1, r]时使用:
int bsearch_1(int l, int r, int x) {
while (l < r) {
int mid = (l + r) >> 1;
if (a[mid] >= x)
r = mid; // check()判断mid是否满足性质
else
l = mid + 1;
}
return l;
}
// 区间[l, r]被划分成[l, mid - 1]和[mid, r]时使用:
int bsearch_2(int l, int r, int x) {
while (l < r) {
int mid = (l + r + 1) >> 1;
if (a[mid] <= x)
l = mid;
else
r = mid - 1;
}
return l;
}
int main() {
printf("%d\n", lower_bound(a, a + 9, 3) - a); // 3
printf("%d\n", upper_bound(a, a + 9, 3) - a); // 5
printf("%d\n", bsearch_1(0, 8, 3));
printf("%d\n", bsearch_2(0, 8, 3));
return 0;
}