数位DP

· · 个人记录

题目描述通常如下:求 [l,r] 内满足条件的数个数 (1\le i\le j\le 10^{18})

可知暴力明显不可做,于是用数位DP。

下面求 [1,x] 满足调条件的数。(以 递归 的方式实现)

以 10 进制为例。

假设

x=\sum_{i=0}^{n-1}(10^ia_{i+1})

我们从高位往下枚举。

于是,我们便可以得到大致的代码:

int dp[N][K];
int dfs(int pos, int k, bool limit) {
    if(pos == 0) return 1;
    if(dp[pos][k] and !limit) return dp[pos][k]; // 已经搜过且木有限制
    int up = (limit ? a[pos] : 9), ans = 0;
    for(int i = 0;i <= up; ++i)
        ans += dfs(pos - 1, /*求与条件有关的东西*/, limit and i == up);  
    if(!limit) dp[pos][k] = ans;
    return ans;                       
}
如果之前已是前缀,而当前有和 $a_i$ 一致,则仍受限制。 上面是偏向模板的总结,实际题目会更复杂,$k$ 可能会占多项,那么 $dp$ 的维数就随着涨。反正这玩意一般不可能炸空间。 调用: ``return dfs(cnt, /*?*/, 1)`` -------- ### 以[一道简单的例题](http://222.180.160.110:1024/contest/3051/problem/2)为例: 1.转化:通过前缀和将答案转化为 $pre_r-pre_{l-1}$。 2.将 $x$ 分解为数位。 ```cpp int solve(int x) { int cnt = 0; while(x) a[++cnt] = x % 10, x /= 10; return dfs(cnt, 0, 1); } ``` 3.数位DP ```cpp int dfs(int pos, int pre, bool limit) { if(pos == 0) return 1; if(!limit and dp[pos][pre]) return dp[pos][pre]; int up = (limit ? a[pos] : 9), ans = 0; for(int i = 0;i <= up; ++i) { if(i == 4 or (i == 2 and pre == 6)) continue; ans += dfs(pos - 1, i, limit and i == a[pos]); } return dp[pos][pre] = ans; } ``` ---------------- 总之,这玩意很板。做多了就会觉得无聊……~~不过可以水很多蓝紫~~