人生第一次Java大数,贴贴代码吧
//k归并排序,给定数组的大小n和k,求最多进行几次比较
//思路就是把n个数均分成k堆,然后递归求解各堆的次数,最后把各堆归并起来
//用map后可以大大降低时间消耗(T过。。。)
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.math.BigInteger;
public class Test{
public static Map<BigInteger,BigInteger>mp;
public static BigInteger dfs(BigInteger n,BigInteger k){
if(mp.containsKey(n))return mp.get(n);
BigInteger ret=BigInteger.ZERO;
BigInteger modd=n.mod(k);
BigInteger each=n.divide(k);
if(n.compareTo(k)<=0){
ret=n.multiply(n.subtract(BigInteger.ONE)).divide(BigInteger.valueOf(2));
}
else{
BigInteger a=dfs(each.add(BigInteger.ONE),k);
BigInteger b=dfs(each,k);
a=a.multiply(modd);
b=b.multiply(k.subtract(modd));
ret=a.add(b);
//merge
BigInteger num1=each.multiply(modd).multiply(k.subtract(BigInteger.ONE));
BigInteger num2=each.subtract(BigInteger.ONE).multiply(k.subtract(modd)).multiply(k.subtract(BigInteger.ONE));
BigInteger num3=k.multiply(k.subtract(BigInteger.ONE)).divide(BigInteger.valueOf(2));
ret=ret.add(num1).add(num2).add(num3);
}
mp.put(n, ret);
return ret;
}
public static void main(String[] agrs){
Scanner cin=new Scanner(System.in);
int t;
t=cin.nextInt();
for(int kase=1;kase<=t;kase++){
BigInteger n,k;
n=cin.nextBigInteger();
k=cin.nextBigInteger();
mp=new HashMap<BigInteger,BigInteger>();
System.out.println("Case "+kase+": "+dfs(n,k));
}
}//end of main
}