首先考虑没两对线,由于所有线都平行于不同的坐标轴,所以这两对线的n-2个坐标都相同的时候共面,然后对于共面的两条线一定是相互垂直的,假设b平行于y轴,a平行于x轴,那么它俩交叉的概率就是b线的x在a线的x的范围内的概率*a线的y在b线的y范围内。这样就可以求得没对直线相交的概率。
根据概率的可加性,结果即为C(n,2)*每对的概率。
最后要用到高精度的乘法和gcd,使用威力强大的java大整数。
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
BigInteger N,D,x,y,four,n18,one,gg;
while(in.hasNext()){
int n, d;
n = in.nextInt();
d = in.nextInt();
if(n == 1 && d == 1){
System.out.println(0);
continue;
}
N = BigInteger.valueOf(n);
D = BigInteger.valueOf(d);
four = BigInteger.valueOf(4);
n18 = BigInteger.valueOf(18);
one = BigInteger.valueOf(1);
x = (N.add(four)).multiply(N.add(four)).multiply(D).multiply(D.add(one.negate()));
y = n18.multiply(N.pow(d));//pow(int)
if(x.equals(y))System.out.println("1");
else{
gg = x.gcd(y);
System.out.print(x.divide(gg));
System.out.print("/");
System.out.println(y.divide(gg));
}
}
}
}
使用新模板:
import java.io.*;
import java.math.BigInteger;
import java.util.StringTokenizer;
class Scan {
BufferedReader buffer;
StringTokenizer tok;
Scan() {
buffer = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext() {
while (tok == null || !tok.hasMoreElements()) {
try {
tok = new StringTokenizer(buffer.readLine());
} catch (Exception e) {
return false;
}
}
return true;
}
String next() {
if (hasNext())
return tok.nextToken();
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
public class Main {
public static void main(String[] args) {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out)));
Scan scan = new Scan();
while(scan.hasNext())
{
BigInteger N,D,x,y,four,eighteen,one,tgcd;
int n,d;
n=scan.nextInt();
d=scan.nextInt();
if(d==1)
{
out.println("0");
continue;
}
N = BigInteger.valueOf(n);
D = BigInteger.valueOf(d);
four = BigInteger.valueOf(4);
eighteen = BigInteger.valueOf(18);
one = BigInteger.valueOf(1);
x = D.multiply(D.subtract(one)).multiply(N.add(four).pow(2));
y = N.pow(d).multiply(eighteen);
tgcd = x.gcd(y);
x = x.divide(tgcd);
y = y.divide(tgcd);
if(x.equals(y))
out.println("1");
else
out.println(x+"/"+y);
}
out.flush();
}
}