ACM-ICPC 2017 Asia HongKong I题 Count the Even Integers【Java大数,递归+记忆化】

传送门:Count the Even Integers

ACM-ICPC 2017 Asia HongKong

题意

求出杨辉三角前 n n n层所有偶数的个数, n n n最大到 1 0 50 10^{50} 1050

思路

打表找规律,设第 n n n层( n n n 0 0 0开始)答案为 a n a_n an,则可 OEIS 得到公式(OEIS A051679
a 0 = a 1 = 0 a 2 n = 3 a n + n ( n − 1 ) / 2 a 2 n + 1 = 2 a n + a n + 1 + n ( n + 1 ) / 2 a_0=a_1=0 \\[1ex] a_{2n}=3a_n+n(n-1)/2 \\[1ex] a_{2n+1} = 2a_n+a_{n+1}+n(n+1)/2 a0=a1=0a2n=3an+n(n1)/2a2n+1=2an+an+1+n(n+1)/2

写Java大数递归的时候,注意用map记忆化一下,否则MLE。

AC代码(Java)

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
	
	static BigInteger zero = BigInteger.ZERO;
	static BigInteger one = BigInteger.ONE;
	static BigInteger two = BigInteger.valueOf(2);
	static BigInteger three = BigInteger.valueOf(3);
	static Map<BigInteger,BigInteger>dp = new HashMap<>();

	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		while(cin.hasNextBigInteger()) {
			BigInteger n = cin.nextBigInteger();
			BigInteger ans = f(n.add(one));
			System.out.println(ans);
		}
	}
	
	static BigInteger f(BigInteger n) {
		if(dp.get(n)!=null) return dp.get(n); 
		if(n==zero||n==one) {
			return zero;
		}
		BigInteger res;
		if(n.mod(two)==zero) {
			BigInteger h = n.divide(two); // n/2
			res = three.multiply(f(h)) // 3*f(h)
					.add(h.multiply(h.subtract(one)).divide(two)); // + h*(h-1)/2
		}
		else {
			BigInteger h = n.subtract(one).divide(two); // (n-1)/2
			res = two.multiply(f(h)) // 2*f(h)
					.add(f(h.add(one))) // + f(h+1)
					.add(h.multiply(h.add(one)).divide(two)); // + h*(h+1)/2
		}
		dp.put(n, res); // dp[n]=res;
		return res;
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nefu-ljw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值