Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Increasing Subsequence

#include <bits/stdc++.h>
using namespace std;

const int N = 2e5 + 5, lg = 30;
int child[N * lg][2], dp[2 * N * lg];
int sz = 1;

int get_bit(int x, int i) { return (x >> i) & 1; }

void insert(int x, int val) {
    int p = 1;
    for (int i = lg - 1; i >= 0; i--) {
        int bit = get_bit(x, i);
        if (!child[p][bit]) {
            child[p][bit] = ++sz;
        }

        p = child[p][bit];
        dp[p] = max(dp[p], val);
    }
}

// Max dp value for all nodes that are < x.
int query(int x) {
    int p = 1, ans = 0;
    for (int i = lg - 1; i >= 0; i--) {
        int bit = get_bit(x, i);
        if (bit) {
            int lchild = child[p][0];
            ans = max(ans, dp[lchild]);
        }
        p = child[p][bit];
    }
    return ans;
}

void reset() {
    for (int i = 0; i <= sz; i++) {
        child[i][0] = child[i][1] = dp[i] = 0;
    }
    sz = 1;
}

void solve(vector<int> &a) {
    int n = a.size();

    int ans = 0;
    for (int i = 0; i < n; i++) {
        int dp_val = 1 + query(a[i]);
        insert(a[i], dp_val);
        ans = max(ans, dp_val);
    }

    cout << ans << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    solve(a);
}