0
点赞
收藏
分享

微信扫一扫

【DP】 HDOJ 4933 Miaomiao's Function


BC的官方题解。。。



注意到 f(0) = 0 , 其余的 f(x) = x % 9 , 如果f(x) = 0 那么 f(x) = 9. 于是 f(0) 肯定是一个 Trick。 那么就需要判定是否 Answer = 0 。 挑选 500 个大质数进行计算,如果答案 Mod 质数 都为 0 。那么就可以认为是 0. 否则对于 9 取摸, 得到 f(Answer) 然后再次进行计算即可。 这里注意一下,题目的第一个版本是求 g(0)+...+g(N)。但是我用Microsoft Azure的话也就能跑出 6 组 f(Answer)=0的情况(N = 0,2755,7243,275608,724390) 并且毫无规律,所以只能改成 L ~ R 的计算。 明显这个数位 DP 满足减法,那么我们计算 L~R 的答案就可以直接 R的答案 - (L-1) 的答案 计算的方式为 dp[N][3] 的数位 dp , N 为位数枚举, 3 为状态: 0.前面都是前导 0 1.下一位应该+ 2.下一位应该- 那么状态转移 0 如果当前位是0 转移到 0 0 如果当前位不是0 转移到 2 1 -> 2 2 -> 1 dpnum[N][3] 为此状态下后面有多少个数字,诸位累加即可。



用java的话就没有那么麻烦。。。


import java.util.*;
import java.math.*;
public class Main
{
	static class node
	{
		public BigInteger s = BigInteger.ZERO, c = BigInteger.ZERO;
	}
	public static node dp[] = new node[105];
	public static int bt[] = new int[105];
	public static int bn, top;
	public static node dfs(int pos, int limit)
	{
		node t = new node();
		if(pos == 0) {
			t.c = BigInteger.ONE;
			return t;
		}
		if(limit == 0 && dp[pos].c.compareTo(BigInteger.ZERO) != 0) return dp[pos];
		int a = pos == top ? 1 : 0;
		int b = limit == 1 ? bt[pos] : 9;
		for(int i = a; i <= b; i++) {
			node tt = dfs(pos - 1, limit == 1 && bt[pos] == i ? 1 : 0);
			t.c = t.c.add(tt.c);
			t.s = t.s.add(tt.s);
			if((top - pos) % 2 == 0) t.s = t.s.add(tt.c.multiply(BigInteger.valueOf(i)));
			else t.s = t.s.subtract(tt.c.multiply(BigInteger.valueOf(i)));
		}
		if(limit == 0) dp[pos] = t;
		return t;
	}
	public static BigInteger g(BigInteger t)
	{
		if(t.compareTo(BigInteger.valueOf(-1)) == 0 || t.compareTo(BigInteger.ZERO) == 0) return BigInteger.ZERO;
		bn = 0;
		while(t.compareTo(BigInteger.ZERO) != 0) { 
			bt[++bn] = t.mod(BigInteger.TEN).intValue();
			t = t.divide(BigInteger.TEN);
		}
		BigInteger ans = BigInteger.ZERO;
		for(top = 1; top <= bn; top++) {
			for(int i = 0; i < 105; i++) dp[i] = new node();
			ans = ans.add(dfs(top, top == bn ? 1 : 0).s);
		}
		return ans;
	}
	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		int _ = scanner.nextInt();
		BigInteger a, b, ans, t;
		while(_-- != 0) {
			a = scanner.nextBigInteger();
			b = scanner.nextBigInteger();
			a = a.subtract(BigInteger.ONE);
			ans = g(b).subtract(g(a));
			if(ans.compareTo(BigInteger.ZERO) == 0) System.out.println("Error!");
			else {
				t = ans.mod(BigInteger.valueOf(9));
				if(t.compareTo(BigInteger.ZERO) == 0) t = BigInteger.valueOf(9);
				ans = ans.mod(t).add(t).mod(t);
				System.out.println(ans);
			}
		}
	}
}




举报

相关推荐

0 条评论