HDU5179 beautiful number 题解 数位DP

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5179

题目大意:
给你一个数 \(A = a_1a_2 \cdots a_n\) ,我们称 \(A\) 为“漂亮的数”当且仅当 \(a[i] \ge a[i+1]\)\(1 \le i \lt n\)) 并且 \(a[i]\) mod \(a[j] = 0\)\(1 \le i \lt n, i \lt j \le n\)),比如 \(931\) 就是一个漂亮的数。

求区间 \([L,R]\) 范围内有多少“漂亮的数”。

问题分析:
本题使用 数位DP 解决。
首先,要注意一个条件:

  • 对于任意 \(i \lt j\)\(a[i]\) mod \(a[j] = 0\)

这其实等同于对于任意满足条件 \(i \le k \lt j\)\(k\)\(a[k]\) mod \(a[k+1] = 0\)

即:对于当前位置 \(pos\) ,它的前一位要么一直都是 \(0\) ,要么 \(a[pos+1]\) (即 \(pos\) 位的高一位)能被 \(a[pos]\) 整除。

我们可以开函数 dfs(int pos, int pre, bool limit) 来解决这个问题,其中:

  • pos 表示当前所处的数位;
  • pre 表示前一位的数值;
  • limit 表示当前是否处于限制状态。

实现代码如下:

#include <bits/stdc++.h>
using namespace std;
int f[33][10], a[33];
void init() {
    memset(f, -1, sizeof(f));
}
int dfs(int pos, int pre, bool limit) {
    if (pos < 0) return 1;
    if (!limit && f[pos][pre] != -1) return f[pos][pre];
    int up = limit ? a[pos] : 9;
    int down = pre ? 1 : 0;
    int tmp = 0;
    for (int i = down; i <= up; i ++) {
        if (pre && pre % i) continue;
        tmp += dfs(pos-1, i, limit && i==up);
    }
    if (!limit) f[pos][pre] = tmp;
    return tmp;
}
int get_num(int x) {
    int pos = 0;
    while (x) {
        a[pos++] = x % 10;
        x /= 10;
    }
    return dfs(pos-1, 0, true);
}
int T, L, R;
int main() {
    init();
    scanf("%d", &T);
    while (T --) {
        scanf("%d%d", &L, &R);
        printf("%d\n", get_num(R)-get_num(L-1));
    }
    return 0;
}
posted @ 2019-12-02 18:03  quanjun  阅读(109)  评论(0编辑  收藏  举报