这题的递推很难,递推结果为:n = 2*k+1 ,f(n) = 4*f(k)+6*k;n = 2*k,f(n) = 2*f(k)+2*f(k-1)+4*k-4
这里要用到HashMap存每次得到的信息,不然会超时,接下来说一下它的用法
建立HashMap: public static HashMap<BigInteger,BigInteger> map = new HashMap<BigInteger,BigInteger>();
插入元素:map.put(one, zero);
判断有无元素n:map.containsKey(n)获得n元素对应的值:map.get(n);
代码如下:
import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class Main {
public static BigInteger zero = BigInteger.ZERO;
public static BigInteger one = BigInteger.ONE;
public static BigInteger two = BigInteger.valueOf(2);
public static BigInteger three = BigInteger.valueOf(3);
public static BigInteger four = BigInteger.valueOf(4);
public static HashMap<BigInteger,BigInteger> map = new HashMap<BigInteger,BigInteger>();
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
map.put(one, zero);
map.put(two, zero);
map.put(three,BigInteger.valueOf(6));
while(cin.hasNext())
{
BigInteger n;
n = cin.nextBigInteger();
System.out.println(fun(n));
}
}
public static BigInteger fun(BigInteger n)
{
if(map.containsKey(n))
return map.get(n);
BigInteger ans,temp = n.mod(two);
BigInteger k = n.divide(two);
if(temp.compareTo(one) == 0)
ans = fun(k).multiply(four).add(k.multiply(BigInteger.valueOf(6)));
else{
BigInteger ans1 = fun(k).multiply(two);
BigInteger ans2 = fun(k.subtract(one)).multiply(two);
ans1 = ans1.add(ans2);
ans2 = k.multiply(four).subtract(four);
ans = ans1.add(ans2);
}
map.put(n,ans);
return ans;
}
}