Dp练习 -Sakura数 简单数位DP

本文介绍了一种简单的数位动态规划方法,通过示例代码详细解释了如何利用DP解决特定问题,包括处理前导0及数据溢出的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写图片描述

思路:简单数位DP,dp[pos][pre]表示枚举到pos位时前一位为pre。
考虑前导0以及数据范围自然溢出。

Code:

#include <bits/stdc++.h>
#define LL unsigned long long
using namespace std;
const int AX = 20+2;
int a[AX];
LL dp[AX][15];

LL dfs( int pos , int pre , bool lead , bool lim ){
    if( pos == -1 ) return 1;
    if( !lim && !lead && dp[pos][pre] != -1 ) return dp[pos][pre];
    LL ans = 0;
    int up = lim ? a[pos] : 9 ;
    for( int i = 0 ; i <= up ; i++ ){
        if( pre == -1 || abs( pre - i ) >= 2 ){
            if( lead && i == 0 ) ans += dfs( pos - 1 , pre , lead, lim && i == a[pos]);
            else ans += dfs( pos - 1 , i , lead && i == 0 , lim && i == a[pos] );
        }
    }
    if( !lim && !lead ) dp[pos][pre] = ans;
    return ans ;
}

LL solve( LL x ){   
    int tot = 0 ;
    while( x ){
        a[tot++] = x % 10;
        x /= 10;
    }
    return dfs( tot - 1 , -1 ,  true , true );
}

int main(){
    LL l , r;
    cin >> l >> r;
    memset( dp , -1 , sizeof(dp) );
    //printf("%lld\n",solve(r)-solve(l-1));
    cout << solve(r) - solve(l-1);
    return 0 ;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值