UESTC 250 数位DP

点击打开链接

题意:中文

思路:加个flag标记一下是不是前导为0就可以了

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const ll INF=0x3f3f3f3f3f3f3f3fll;
const int maxn=5010;
int dig[30];
ll dp[20][10][2];
ll dfs(int pos,int lim,int pre,int flag){
    if(pos<0){
        if(flag) return 0;
        else return 1;
    }
    if(!lim&&dp[pos][pre][flag]!=-1) return dp[pos][pre][flag];
    int las=lim?dig[pos]:9;
    ll ret=0;
    for(int i=0;i<=las;i++){
        if(flag==1){
            if(i==0) ret+=dfs(pos-1,lim&&(i==las),0,1);
            else ret+=dfs(pos-1,lim&&(i==las),i,0);
        }else if(abs(i-pre)>=2) ret+=dfs(pos-1,lim&&(i==las),i,0);
    }
    if(!lim) dp[pos][pre][flag]=ret;
    return ret;
}
ll slove(ll n){
    if(n==0) return 0;
    int len=0;
    while(n){
        dig[len++]=n%10;
        n/=10;
    }
    return dfs(len-1,1,0,1);
}
int main(){
    memset(dp,-1,sizeof(dp));
    ll n,m;
    while(scanf("%lld%lld",&n,&m)!=-1){
        printf("%lld\n",slove(m)-slove(n-1));
    }
    return 0;
}

你可能感兴趣的:(数位DP)