-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathutils.cpp
72 lines (61 loc) · 1.62 KB
/
utils.cpp
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <bits/stdc++.h>
using namespace std;
#define REP(i, n) for (int i = 0; i < (n); i++)
#define all(x) (x).begin(), (x).end()
#define x first
#define y second
typedef long long ll;
const double EPS = 1e-9;
const int INF = 1<<30;
const ll INFLL = 1LL<<60;
template<typename T>
unordered_map<T,int> scale_to_consecutive_integers(vector<T> input) {
sort(all(input));
input.resize(unique(all(input)) - input.begin());
unordered_map<T, int > res;
REP(i, (int)input.size())
res[input[i]] = i;
return res;
}
namespace DiscreteSearchings {
namespace Boolean {
pair<ll, ll> binary_search_for_change_first_false(ll p, ll q, function<bool(ll)> func) {
assert(func(p) == true);
assert(func(q) == false);
while (p + 1 < q) {
ll mid = (p + q) / 2;
if (func(mid))
p = mid;
else
q = mid;
}
return {p, q};
}
pair<ll, ll> binary_search_for_change_first_true(ll p, ll q, function<bool(ll)> func) {
return binary_search_for_change_first_false(p, q, [func](ll x){return !func(x);});
}
}
namespace Ternary {
template<typename T>
pair<T, ll> ternary_search_minimize(ll p, ll q, function<T(ll)> func) {
while (q - p >= 3) {
int l = p + (q-p)/3,
r = p + 2*(q-p)/3;
if (func(l) <= func(r))
q = r;
else
p = l;
}
vector<T> vals;
for (ll i = p; i <= q; i++)
vals.emplace_back(func(i));
return {*min_element(all(vals)), p + min_element(all(vals)) - vals.begin() };
}
template<typename T>
pair<T, ll>ternary_search_maximize(ll p, ll q, function<T(ll)> func) {
auto res = ternary_search_minimize(p, q, [func](ll x){return -func(x);});
res.first *=-1;
return res;
}
}
}