題目鏈接
http://codeforces.com/gym/101503/attachments
題目大意
信封問題
給你兩個整數K,N(1 ≤ N ≤ 100; 0 ≤ K ≤ N) ,K封信裝對,其他全裝錯,問你出現這種情況的概率是多少
(如果是0,則輸出0,否則以分數形式輸出【1也是】)
思路
典型的錯排問題
全錯排的遞推式
// d[i] 表示一共i封信全都裝錯的種類數量
d[1] = 0;
d[2] = 1;
d[i] = (i - 1) * (d[i-1] + d[i-2]);
所以題目中情況的種類數就是C(n - k, n) * d[n - k];
所有情況的數量就是n!
把答案化簡一下就是d[n - k] / (k! * (n - k)!)
很明顯式子中的數會很大,上高精度的話這題就很簡單了
大整數類BigInteger用法(整型)
可以參考此博客http://blog.csdn.net/hqd_acm/article/details/5751686
BigInteger基本用法和BigDecimal差不多,但是BigInteger多了很多實用的函數,比如gcd
代碼
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int k = in.nextInt();
int n = in.nextInt();
if(k + 1 == n) {
System.out.println("0");
return ;
}
BigInteger d[] = new BigInteger[105];
d[0] = BigInteger.ONE;
d[1] = BigInteger.ZERO;
d[2] = BigInteger.ONE;
for(int i = 3; i <= n; ++i) {
d[i] = BigInteger.valueOf(i-1).multiply(d[i-1].add(d[i-2]));
}
BigInteger a = d[n-k];
BigInteger b = BigInteger.ONE;
for(int i = 2; i <= k; ++i) b = b.multiply(BigInteger.valueOf(i));
for(int i = 2; i <= n-k; ++i) b = b.multiply(BigInteger.valueOf(i));
BigInteger g = a.gcd(b);
System.out.println(a.divide(g) + "/" + b.divide(g));
in.close();
}
}
總結
這題Java代碼寫挫了,平時一直寫C++,Java被忽視了啊