在n到m中 有多少个1 (数位dp)

写出来了  经过了简单的验证

总体思路比较简单  只需要记录出现1的次数  在最后遍历到1 的时候 直接加上我们所统计的数字 在加上记忆化 更加省时

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<map>
#include<vector>
#include<math.h>
#include<string>
using namespace std;
#define INF 0x3f3f3f3f
#define LL long long
#define N 106
#define Lson rood<<1
#define Rson rood<<1|1
LL dp[20][20][20],d[20];
LL dfs(int now,int w,int tot,int fp)
{
    if(now==1) return tot;
    if(!fp&&dp[now][w][tot]!=-1) return dp[now][w][tot];
    int ma=(fp?d[now-1]:9);
    LL ans=0;
    for(int i=0;i<=ma;i++)
        ans+=dfs(now-1,i,tot+(i==1?1:0),fp&&i==ma);
    if(!fp&&dp[now][w][tot]==-1) dp[now][w][tot]=ans;
    return ans;
}
LL calc(LL x)
{
    if(x==0) return 0;
    LL xxx=x,sum=0;
    int len=0;
    while(xxx)
    {
        d[++len]=xxx%10;
        xxx/=10;
    }
    for(int i=0;i<=d[len];i++)
        sum+=dfs(len,i,(i==1?1:0),i==d[len]);
    return sum;
}
int main()
{
    LL n,m;
    while(scanf("%lld%lld",&n,&m)!=EOF)
    {
        memset(dp,-1,sizeof(dp));
        printf("%lld
",calc(m)-calc(n-1));
    }
    return 0;
}

 来源于@zhber

原文地址:https://www.cnblogs.com/a719525932/p/7755442.html