二分模板
1.二分模板
二分的本质并不是单调性,而是一种边界。
定义某种性质,使得右半边的部分全部满足该种性质,而左半边的部分全部都不满足该种性质。而二分可以寻找性质的边界。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| while (low < high) { int mid = low + high + 1 >> 1; if (check(mid)) low = mid; else high = mid - 1; }
while (low < high) { int mid = low + high >> 1; if (check(mid)) high = mid; else low = mid + 1; }
const double eps = 1e-6; while (high - low > 1e-8) { double mid = (low + high) / 2; if (check(mid)) low = mid; else high = mid; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| #include<iostream> using namespace std;
const int MAX = 1e6 + 10;
int n, m, arr[MAX];
int main() { scanf("%d %d", &n, &m); for (int i = 0; i < n; ++i) scanf("%d", &arr[i]); for (int i = 0; i < m; ++i) { int x; scanf("%d", &x); int low = 0, high = n - 1; while (low < high) { int mid = low + high >> 1; if (arr[mid] >= x) high = mid; else low = mid + 1; } if (arr[low] != x) printf("-1 -1\n"); else { printf("%d ", low); int low = 0, high = n - 1; while (low < high) { int mid = low + high + 1 >> 1; if (arr[mid] <= x) low = mid; else high = mid - 1; } printf("%d\n", low); } } return 0; }
|