Skip to content

Commit

Permalink
improves longest increasing subsequence
Browse files Browse the repository at this point in the history
  • Loading branch information
iagorrr committed Aug 8, 2024
1 parent 2a4bfc1 commit 88675ae
Showing 1 changed file with 38 additions and 28 deletions.
66 changes: 38 additions & 28 deletions algorithms/dynamic-programming/longest-increasing-subsequence.cpp
Original file line number Diff line number Diff line change
@@ -1,43 +1,53 @@
template <typename T>
pair<int, vector<int>> lis(const vector<T> &xs) {
int n = xs.size();
/*~================BEGIN LONGEST INCREASING SUBSEQUENCE=================~*/
#define len(j) (int)j.size()
#define all(j) j.begin(), j.end()
#define rall(j) j.rbegin(), j.rend()
#define rep(i, a, b) \
for (common_type_t<decltype(a), decltype(b)> i = a; i < b; i++)

using vi = vector<int>;

vector<T> dp(n + 1, numeric_limits<T>::max());
dp[0] = numeric_limits<T>::min();
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;
vector<int> psx(n);
int sz = 0;
vi psx(n);

for (int i = 0; i < n; i++) {
auto it = lower_bound(dp.begin(), dp.end(), xs[i]);
auto pos = (int)(it - dp.begin());
rep(i, 0, n) {
int pos = lower_bound(all(dp), xs[i]) - dp.begin();

sz = max(sz, pos);
sz = max(sz, pos);

dp[pos] = xs[i];
dp[pos] = xs[i];

psx[i] = pos;
}
psx[i] = pos;
}

return {sz, psx};
return {sz, psx};
}

template <typename T>
vector<int> get_idx(vector<T> xs) {
auto [sz1, psx1] = lis(xs);
vi get_idx(vector<T> xs) {
int n = xs.size();

reverse(xs.begin(), xs.end());
for (auto &xi : xs) xi = -xi;
auto [sz1, psx1] = lis(xs, n);

auto [sz2, psx2] = lis(xs);
// reverse(all(xs));
transform(rall(xs), xs.begin(), [](T x) { return -x; });
// for (auto& xi : xs) xi = -xi;

vector<int> ans;
int _n = xs.size();
for (int i = 0; i < _n; i++) {
int l = psx1[i];
int r = psx2[_n - i - 1];
if (l + r - 1 == sz1) ans.push_back(i);
}
auto [sz2, psx2] = lis(xs, n);

return ans;
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;
}

/*~=================END LONGEST INCREASING SUBSEQUENCE==================~*/

0 comments on commit 88675ae

Please sign in to comment.