HDOJ2089 不要62 --- 数位dp

拜拜、爱过 提交于 2019-12-04 13:51:37

题意:给定区间[n,m],1<=n<m<1,000,000

问有多少个数不含4,且不含62

题解:数位dp的典型题,参考 https://blog.csdn.net/jk211766/article/details/81474632 

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,m;
int d[10][3];
int number[10];

// pos: 当前位置
// sta: 前1位是否是6
int dp(int pos,int sta,bool limit) {
    if(pos == -1) return 1;
    if(d[pos][sta] != -1 && !limit) return d[pos][sta];
    int up = (limit == true ? number[pos] : 9);
    int tot = 0;
    for(int i = 0;i <= up;i++) {
        if(i == 4) continue;
        if(sta == 1 && i == 2) continue;
        tot += dp(pos-1,i==6,limit&&i==number[pos]);
    }
    if(!limit) d[pos][sta] = tot;
    return tot;
}

int solve(int n) {
    memset(d,-1,sizeof(d));
    int tot = 0;
    while(n) {
        number[tot++] = n % 10;
        n /= 10;
    }
    return dp(tot-1,0,true);
}

int main() {
    while(scanf("%d%d",&n,&m) != EOF) {
        if(n == 0 && m == 0) break;
        printf("%d\n",solve(m)-solve(n-1));
    }

    return 0;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!