錯排
n各有序的元素應有n!種不同的排列。如若一個排列式的所有的元素都不在原來的位置上,則稱這個排列為錯排。任給一個n,求出1,2,……,n的錯排個數Dn共有多少個。
遞迴關係式為:D(n)=(n-1)(D(n-1)+D(n-2))
D(1)=0,D(2)=1
可以得到:
錯排公式為 f(n) = n![1-1/1!+1/2!-1/3!+……+(-1)^n*1/n!]
其中,n!=1*2*3*.....*n,
特別地,有0!=0,1!=1.
解釋:
n 個不同元素的一個錯排可由下述兩個步驟完成:
第一步,“錯排” 1 號元素(將 1 號元素排在第 2 至第 n 個位置之一),有 n - 1 種方法。
第二步,“錯排”其餘 n - 1 個元素,按如下順序進行。視第一步的結果,若1號元素落在第 k 個位置,第二步就先把 k 號元素“錯排”好, k 號元素的不同排法將導致兩類不同的情況發生:
1、 k 號元素排在第1個位置,留下的 n - 2 個元素在與它們的編號集相等的位置集上“錯排”,有 f(n -2) 種方法;
2、 k 號元素不排第 1 個位置,這時可將第 1 個位置“看成”第 k 個位置(也就是說本來準備放到k位置為元素,可以放到1位置中),於是形成(包括 k 號元素在內的) n - 1 個元素的“錯排”,有 f(n - 1) 種方法。據加法原理,完成第二步共有 f(n - 2)+f(n - 1) 種方法。
根據乘法原理, n 個不同元素的錯排種數
f(n) = (n-1)[f(n-2)+f(n-1)] (n>2) 。
總結公式: A[i]=(i-1)x(A[I-1]+A[I-2]); A[0]=0,A[1]=0,A[2]=1; 牢記!!!代碼:
import java.util.*;import java.io.*;import java.math.BigInteger;public class CuoPai {public static void main(String[] args) {Scanner sc=new Scanner(new BufferedInputStream(System.in));int m=sc.nextInt();int n=sc.nextInt();if(n<=m){System.out.println(getCount(n));}}public static BigInteger getCount(int n){BigInteger big[]=new BigInteger[n+1];big[0]=BigInteger.ZERO;big[1]=BigInteger.ZERO;big[2]=BigInteger.ONE;for(int i=3;i<=n;i++){big[i]=BigInteger.valueOf(i-1).multiply(big[i-1].add(big[i-2]));}return big[n];}}
組合: 公式 C(m,n)=A(m,n)/n!=m!/(m-n)!/n! 第一種方法:利用公式求組合
import java.util.*;import java.io.*;import java.math.BigInteger;public class zhuHe {public static void main(String args[]) {Scanner sc = new Scanner(new BufferedInputStream(System.in));int m = sc.nextInt();int n = sc.nextInt();if (n <= m) {System.out.println(getCount(m).divide(getCount(m - n)).divide(getCount(n)));}}public static BigInteger getCount(int n) {BigInteger big[] = new BigInteger[n + 1];big[0] = BigInteger.ONE;big[1] = BigInteger.ONE;BigInteger sum = BigInteger.ONE;for (int i = 1; i <= n; i++) {big[i] = big[i - 1].multiply(BigInteger.valueOf(i));}return big[n];}}
第二種方法 利用演算法求組合
import java.util.*;import java.io.*;import java.math.BigInteger;public class zhuHe {public static void main(String[] args) {Scanner sc = new Scanner(new BufferedInputStream(System.in));int m = sc.nextInt();int n = sc.nextInt();if (n <= m)System.out.println(getCount(m, n));}public static BigInteger getCount(int m, int n) {if (n == 0)return BigInteger.ONE;BigInteger sum1 = BigInteger.ONE;BigInteger sum2 = BigInteger.ONE;for (int i = 0; i < n; i++) {sum1 = sum1.multiply(BigInteger.valueOf(m - i));sum2 = sum2.multiply(BigInteger.valueOf(i + 1));}return sum1.divide(sum2);}}