-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbisect.h
35 lines (30 loc) · 811 Bytes
/
bisect.h
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
/*
* bisect header.
* written by Shuangquan Li, [email protected]
* created on 2016-8-23
*/
#ifndef __BISECT_H__
#define __BISECT_H__
// bisection
// return the min i in [l, r] which isok(i) is true.
template<typename IntegerType, typename UnaryPredicate>
IntegerType bisect_min(IntegerType l, IntegerType r, UnaryPredicate isok) {
while (l < r) {
IntegerType mid = (l + r) >> 1;
if (isok(mid)) r = mid;
else l = mid + 1;
}
return l;
}
// return the max i in [l, r] which isok(i) is true.
template<typename IntegerType, typename UnaryPredicate>
IntegerType bisect_max(IntegerType l, IntegerType r, UnaryPredicate isok) {
while (l < r) {
IntegerType mid = (l + r + 1) >> 1;
if (isok(mid)) l = mid;
else r = mid - 1;
}
return l;
}
/* eof */
#endif