Pair the people#11288

Pair the people (Editorial)

Let represent the number of different ways that all people can join the dance. For example,

Consider the -th person:

Thus we have the relation:

f(n) = f(n - 1) + (n - 1) \cdot f(n - 2)

Example

Let there be n = 3 people. They can join the dance in ways:

Compute using a formula:

f(3) = f(2) + 2 \cdot f(1) = 2 + 2 \cdot 1 = 4

Algorithm implementation

Declare a modulo constant and an array to store the answers: dp[n] = f(n).

#define MOD 1000000007
long long dp[100001];

Read the input value of .

scanf("%d", &n);

Compute the values sequentially for f(1), f(2), ..., f(n), storing each result in the array.

dp[1] = 1; dp[2] = 2;
for (i = 3; i <= n; i++)
  dp[i] = (dp[i - 1] + (i - 1) * dp[i - 2]) % MOD;

Print the answer.

printf("%lld\n", dp[n]);

Python implementation

Declare the modulo constant , which will be used for the calculations.

MOD = 1000000007

Read the input value of .

n = int(input())

Declare a list for storing the results, where dp[n] = f(n).

dp = [0] * (n + 1)

Compute the values sequentially for f(1), f(2), ..., f(n), storing each result in the array.

dp[1] = 1
if n > 1: dp[2] = 2
for i in range(3, n + 1):
  dp[i] = (dp[i - 1] + (i - 1) * dp[i - 2]) % MOD

Print the answer.

print(dp[n])