[Ybtoj Chapter 1 Example 1] Wrong arrangement [Recursion]

Insert picture description here
Insert picture description here


Problem solving ideas

First set f [n] f[n]f [ n ] meansnnn number of solutions that satisfy the meaning of the question.
First, set a position k, if we put n at positionk (k ≠ n) (k ≠ n)(k=n ) , then(n − 1) (n − 1)( n 1 ) kinds of placement methods Next, we consider the placement of k.

  • k is placed in the position of n:
    if it is placed this way, the remaining unordered elements will be left (n − 2) (n − 2)( n 2 ) , which is
    equivalent to putting that(n − 2) (n − 2)( n 2 ) elements are staggered, the number of schemes is $f [n − 2] $.
  • k is not placed at the position of n: in
    this case, the disordered elements will have (n − 1) (n − 1)( n 1 ) , which is
    equivalent to putting(n − 1) (n − 1)( n 1 ) elements are staggered, the number of schemes isf [n − 1] f [n − 1]f[n1] .

So in (n − 1) (n − 1)In the case of ( n 1 ) , there isf [n − 1] + f [n − 2] f [n − 1] + f [n − 2]f[n1]+f [ n 2 ] kinds of placement methods.
The total number of solutions is(n − 1) × (f [n − 1] + f [n − 2]) (n − 1) × (f [n − 1] + f [n − 2])(n1)×(f[n1]+f[n2]) .


Code

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;

long long n,f[110];

int main(){
    
    
	scanf("%lld",&n);
	f[1]=0,f[2]=1;
	for(int i=3;i<=n;i++)
		f[i]=(i-1)*(f[i-1]+f[i-2]);
	printf("%lld",f[n]);
}

Guess you like

Origin blog.csdn.net/kejin2019/article/details/111407442