洛谷 P2602(数位DP)

### 洛谷 P2602 题目链接 ###

 

题目大意:给你一个区间,问你区间所有数字中,0、1、2 .... 9 的个数的总和分别为多少。

 

分析:

枚举 0 ~ 9 进行数位 DP 即可。

注意记忆化搜索:必须要用到第二维来表示,前 1 ~ pos 位,某个数(0 ~ 9)的个数。

例如,我们在求这个区间中 2 的个数,直接看的话,后 pos 位 的 2 的个数好像与 1 ~ pos位 上有多少个 2 并无联系(在 !limit 情况下),那为什么还要开第二维呢?

实际算上来你会发现:比如当枚举到 222 这个数时,很显然 pos==0 后,2 的总个数(即 sum)为 3 。而如果我们枚举到 第 2 位 (十位上)时,用到的记忆化是 dp[2] ,它只记录的是后两位中,有 22 这个数,即两个 2 ,而实际我们求 222 时,应该使程序返回的是 sum== 3 。故我们需要记忆化 dp[2][1] ,让在前 1 ~ pos 位已有一个 2 的时候,返回 sum== 3 (即这个 1 最后会再加上后面两个 2 的个数 ,对应的是 22 )

  

代码如下:

 

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
typedef long long ll;
ll n,m;
int a[15];
ll dp[15][15];
ll dfs(int pos,int t,int sum,bool lead,bool limit){
    if(pos==0) return sum;
    if(!limit&&!lead&&dp[pos][sum]!=-1) return dp[pos][sum];
    int up=limit?a[pos]:9;
    ll res=0;
    for(int i=0;i<=up;i++){
        if(lead&&i==0) res+=dfs(pos-1,t,sum,true,limit&&i==a[pos]);
        else res+=dfs(pos-1,t,i==t?sum+1:sum,false,limit&&i==a[pos]);
    }
    if(!limit&&!lead) dp[pos][sum]=res;
    return res;
}
ll solve(ll x,int t)
{
    int pos=0;
    while(x){
        a[++pos]=x%10;
        x/=10;
    }
    return dfs(pos,t,0,true,true);
}
int main()
{
    //freopen("test.in","r",stdin);
    //freopen("test.out","w",stdout);
    memset(dp,-1,sizeof(dp));
    scanf("%lld%lld",&n,&m);
    for(int i=0;i<=9;i++){
        if(i!=9) printf("%lld ",solve(m,i)-solve(n-1,i) );
        else printf("%lld\n",solve(m,i)-solve(n-1,i) );
     }
}

 

转载于:https://www.cnblogs.com/Absofuckinglutely/p/11430174.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值