CSES - Increasing Subsequence II
Authors: Benjamin Qi, Óscar Garries, Timothy Gao
Time Complexity:
Let be the number of increasing subsequences of ending on the right of index . Notice that can be calculated as the summation of all where and .
Naively, this gives an solution. In order to speed this up, we can coordinate compress, then range sum.
More specifically, we sort all numbers in 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 , would be the sum of the values at positions in the BIT, where is the index that maps to. We then increase position in the BIT by as preparation for the next element of .
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];int[] sorted = 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!