题目链接
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被忽视了啊