hdu1919(递推+高精度+HashMap)

这题的递推很难,递推结果为: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;
    }    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值