Misalignment
Topic link: Misalignment
Title description
Problem solving ideas
This question is an entry-level (a ghost) recursion.
Let fn f_nfnFor nnLegal permutation of n numbers.
We will nnn number is placed atkkFor k positions, there aren − 1 n-1n−1 middle release method (n! = Kn! = kn!=k)。
There are two cases for the remaining elements:
- Will kkk innnOn n , the remaining elements aren − 2 n-2n−The misalignment of 2 , iefn − 2 f_{n-2}fn−2。
- Will kkk is placed in non-nnIn the position of n , it includeskkThe remaining elements within k aren − 1 n-1n−The misalignment of 1 , namelyfn − 1 f_{n-1}fn−1。
Because we are determining nnConsiderkkafter the position of nIn the case of k , sonnn 's case andkkThe case of k satisfies the principle of multiplication.
Because kkk putnnn and not putnnn is two different cases, so these two cases satisfy the principle of addition.
The recurrence formula is: fn = (n + 1) (fn − 1 + fn − 2) f_n=(n+1)(f_{n-1}+f_{n-2})fn=(n+1)(fn−1+fn−2)
Wheref 1 = 0 f_1=0f1=0, f 2 = 1 f_2=1 f2=1。
code
#include<iostream>
#include<cstdio>
#define int long long
using namespace std;
int n;
int f[30];
signed main()
{
cin>>n;
f[1]=0,f[2]=1;
for(int i=3;i<=n;i++)
f[i]=(i-1)*(f[i-1]+f[i-2]);
cout<<f[n]<<endl;
}