CSES - Permutations II
Author: Dustin Miao
Solution 1 - Connected Components DP
Define as the number of valid configurations of the numbers from to into "connected components", where value has borders. For instance, the set of intervals would be counted in the state .
- If has no borders, then must point two existing connected compontents.
- If has one border, then must be appended on to an existing connected component.
- If has two borders, it must be inserted as its own connected component.
This corresponds to the following transitions:
The base case is , and the final answer is .
Implementation
Time Complexity:
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 .
Implementation
Time Complexity:
Python
N = int(input())dp = [0] * (N + 1)dp[0], dp[1] = 1, 1for 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]) % 1000000007print(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!