LightOJ - 1140 How Many Zeroes?(数位DP)

来源:互联网 发布:mc9s12xs128单片机调试 编辑:程序博客网 时间:2024/05/16 05:37

题目大意:问[l,r]这个范围内的数,有多少个0

解题路上:用dp[has][cur]表示到了第i位,拥有0的数量为has的情况下有多少个零,接着就是数位DP了

#include <cstdio>#include <cstring>typedef long long LL;const int N = 35;int bit[N];int cas = 1;LL dp[N][N];LL dfs(int cur, int limit, LL has, int preZero) {    if (cur == -1) {        if (preZero) return 1;        else return has;    }    if (!limit && !preZero && dp[has][cur] != -1) return dp[has][cur];    int n = limit ? bit[cur]: 9;    LL ans = 0;    for (int i = 0; i <= n; i++) {        //前导0        if (preZero) ans += dfs(cur - 1, limit && i == n, 0, preZero && i == 0);        else if (i == 0) ans += dfs(cur - 1, limit && i == n, has + 1, 0);        else ans += dfs(cur - 1, limit && i == n, has, 0);    }    if (!limit &&!preZero) dp[has][cur] = ans;    return ans;}LL DP(LL num) {    if (num < 0) return 0;    int cnt = 0;    while (num) {        bit[cnt++] = num % 10;        num /= 10;    }    memset(dp, -1, sizeof(dp));    return dfs(cnt - 1, 1, 0, 1);}void solve() {    LL l, r;    scanf("%lld%lld", &l, &r);    LL ansR = DP(r);    LL ansL = DP(l - 1);    printf("Case %d: %lld\n", cas++, DP(r) - DP(l - 1));}int main() {    int test;    scanf("%d", &test);    while (test--) solve();    return 0;}
0 0
原创粉丝点击