【hdu2089】不要62 数位dp

本文介绍了一种使用递归状态机解决特定数字序列问题的方法。通过动态规划算法,避免了无效数字组合,如包含4或连续2和6的情况。代码实现了从高位到低位逐位填充数字的过程,并计算出所有合法序列的数量。

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

传送门:嘿原题在这

注释写的很详细啦

 

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int dp[10][2],a[10];
int l,r,tot;

//pos表示当前位置,pre表示前一个数,sta表示当前的状态,也就是之前是否为6,lim表示当前是否
//是有限制的,就比如说967当我第一个数选择9时第二个数只能选择0~6了,这种情况需要标记其他情况都是0~9
int dfs(int pos,int pre,int sta,int lim)
{
    int cur=0;
    if (pos==0) return 1;//如果执行到0了,当前构成的数可行
    if (!lim&&dp[pos][sta]!=-1) return dp[pos][sta];
    int up=lim?a[pos]:9;
    for (int i=0;i<=up;i++)
    {
        //排除不可能情况
        if (i==4) continue;
        if (pre==6&&i==2) continue;

        cur+=dfs(pos-1,i,i==6,lim&&i==a[pos]);
    }
    if(!lim) dp[pos][sta]=cur;
    return cur;

}

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

int main()
{
    while(~scanf("%d%d",&l,&r)&&(l+r))
    {
        memset(dp,-1,sizeof(dp));
        printf("%d\n",solve(r)-solve(l-1));
    }
    return 0;
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值