-
Notifications
You must be signed in to change notification settings - Fork 2
/
Longest increasing subsequence.cpp
63 lines (44 loc) · 1.08 KB
/
Longest increasing subsequence.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
/*8<
@Title:
Longest Increasing Subsequence
@Description:
Find the pair $(sz, psx)$ where $sz$ is the
size of the longest subsequence and $psx$ is
a vector where $psx_i$ tells the size of the
longest increase subsequence that ends at
position $i$. $get_idx$ just tells which
indices could be in the longest increasing
subsequence.
@Time:
$O(n\log{n})$
>8*/
template <typename T>
pair<int, vi> lis(const vector<T> &xs, int n) {
vector<T> dp(n + 1, numeric_limits<T>::max());
dp[0] = numeric_limits<T>::min();
int sz = 0;
vi psx(n);
rep(i, 0, n) {
int pos =
lower_bound(all(dp), xs[i]) - dp.begin();
sz = max(sz, pos);
dp[pos] = xs[i];
psx[i] = pos;
}
return {sz, psx};
}
template <typename T>
vi get_idx(vector<T> xs) {
int n = xs.size();
auto [sz1, psx1] = lis(xs, n);
transform(rall(xs), xs.begin(),
[](T x) { return -x; });
auto [sz2, psx2] = lis(xs, n);
vi ans;
rep(i, 0, n) {
int l = psx1[i];
int r = psx2[n - i - 1];
if (l + r - 1 == sz1) ans.eb(i);
}
return ans;
}