CSES - Increasing Subsequence II

Authors: Benjamin Qi, Óscar Garries, Timothy Gao


Time Complexity: O(NlogN)\mathcal{O}(N\log N)

Let dp[i]dp[i] be the number of increasing subsequences of xx ending on the right of index ii. Notice that dp[i]dp[i] can be calculated as the summation of all dp[j]dp[j] where j<ij < i and xj<xix_j < x_i.

Naively, this gives an O(N2)\mathcal O(N^2) solution. In order to speed this up, we can coordinate compress, then range sum.

More specifically, we sort all numbers in xx and map each distinct number to its index in the sorted array. This is known as coordinate compression, and it makes the range of the numbers significantly smaller.

With this, we can create a BIT, where each value is initially 0. As we iterate through xx, dp[i]dp[i] would be the sum of the values at positions j<kj<k in the BIT, where kk is the index that xix_i maps to. We then increase position kk in the BIT by dp[i]dp[i] as preparation for the next element of xx.

C++

#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int MX = 2e5 + 5;
int bit[MX];
int n;

Java

import java.io.*;
import java.util.*;
public class increasingsubsequencesII {
static final int mod = (int)(1e9 + 7);
public static void main(String[] args) throws IOException {
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int N = Integer.parseInt(br.readLine());
int[] nums = new int[N];

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!