CSES - Permutations II

Author: Dustin Miao

Solution 1 - Connected Components DP

Define fi,j,kf_{i,j,k} as the number of valid configurations of the numbers from 11 to ii into jj "connected components", where value ii has kk borders. For instance, the set of intervals {[1,6],[2,3,5],[7],[4,8,9]}\{[1,6],[2,3,5],[7],[4,8,9]\} would be counted in the state f9,4,1f_{9,4,1}.

  1. If ii has no borders, then ii must point two existing connected compontents.
  2. If ii has one border, then ii must be appended on to an existing connected component.
  3. If ii has two borders, it must be inserted as its own connected component.

This corresponds to the following transitions:

fi,j,0=j(j+1)fi1,j+1,0+j2fi1,j+1,1+j(j1)fi1,j+1,2fi,j,1=2jfi1,j,0+(2j1)fi1,j,1+(2j2)fi1,j,2fi,j,2=fi1,j1,0+fi1,j1,1+fi1,j1,2\begin{align*} f_{i,j,0}&=j(j+1)f_{i-1,j+1,0}+j^2f_{i-1,j+1,1}+j(j-1)f_{i-1,j+1,2}\\ f_{i,j,1}&=2jf_{i-1,j,0}+(2j-1)f_{i-1,j,1}+(2j-2)f_{i-1,j,2}\\ f_{i,j,2}&=f_{i-1,j-1,0}+f_{i-1,j-1,1}+f_{i-1,j-1,2}\\ \end{align*}

The base case is f0,0,0=1f_{0,0,0}=1, and the final answer is kfn,1,k\sum_k f_{n,1,k}.

Implementation

Time Complexity: O(n2)\mathcal{O}(n^2)

C++

#include <bits/stdc++.h>
const int MOD = 1000000007;
int main() {
int N;
std::cin >> N;
std::vector dp(N + 1, std::vector<std::array<long long, 3>>(N + 2));
for (auto &a : dp)
for (auto &b : a) b.fill(0);

Solution 2 - OEIS

Brute forcing the first few terms and plugging the sequence into OEIS yields OEIS - A002464, which is exactly what we are looking for. This gives us the simpler recurrence ai=(i+1)ai1(i2)ai2(i5)ai3+(i3)ai4a_i=(i+1)a_{i-1} - (i-2)a_{i-2} - (i-5)a_{i-3} + (i-3)a_{i-4}.

Implementation

Time Complexity: O(n)\mathcal{O}(n)

Python

N = int(input())
dp = [0] * (N + 1)
dp[0], dp[1] = 1, 1
for i in range(4, N + 1):
dp[i] = (
(i + 1) * dp[i - 1]
- (i - 2) * dp[i - 2]
- (i - 5) * dp[i - 3]
+ (i - 3) * dp[i - 4]
) % 1000000007
print(dp[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!