Editorial
Let represent the number of different ways that all people can join the dance. For example,
, one person dances by himself;
, for two people, there are two options: either dance separately or as a pair;
Consider the -th person:
If he dances alone, the remaining people can join the dance in ways
The -th person can choose any of the people as a partner. The remaining people can join the dance in ways.
Thus we have the relation:
Example
Let there be people. They can join the dance in ways:
if the third person dances separately: ;
if the third person dances in a pair: .
Compute using a formula:
Algorithm realization
Declare a modulo constant and an array to store the answers: .
#define MOD 1000000007 long long dp[100001];
Read the input value of .
scanf("%d", &n);
Compute the values sequentially for , 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 realization
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 = [0] * (n + 1)
Compute the values sequentially for , 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])