1. 程式人生 > >數位dp模板(Java版)

數位dp模板(Java版)

hdu的不要62那道題

import java.util.Scanner;

public class Main {
    static int[] a = new int[20];
    //dp[pos][sta]表示當前第pos位,前一位是否為6的狀態
    static int[][] dp = new int[20][2];

    //當前位數 上一個數 當前狀態(上一位是否為6) 是否有列舉上界
    static int dfs(int pos, int pre, int sta, boolean limit) {
        //列舉結束
        if (
pos == -1) { return 1; } //記憶化 if (!limit && dp[pos][sta] != -1) { return dp[pos][sta]; } //當前位列舉上界 int up = limit ? a[pos] : 9; int tmp = 0; for (int i = 0; i <= up; i++) { if (pre == 6 &&
i == 2) { continue; } if (i == 4) { continue; } if (i == 6) { tmp += dfs(pos - 1, i, 1, limit && i == a[pos]); } else { tmp += dfs(pos - 1, i, 0, limit && i == a[
pos]); } } if (!limit) { dp[pos][sta] = tmp; } return tmp; } //分解數位 static int solve(int x) { int pos = 0; while (x > 0) { a[pos++] = x % 10; x /= 10; } //從高位列舉 return dfs(pos - 1, -1, 0, true); } public static void main(String[] args) { int l, r; Scanner cin = new Scanner(System.in); while (cin.hasNext()) { l = cin.nextInt(); r = cin.nextInt(); if(l+r==0){ break; } for (int i = 0; i < 20; i++) { dp[i][0] = dp[i][1] = -1; } System.out.println(solve(r) - solve(l - 1)); } } }