codeforces 1036C 数位DP

codeforces 1036C


题意:

给 定 区 间 [ l , r ] , 限 制 条 件 : 给定区间[l,r],限制条件: [l,r]

  • 所 有 数 位 上 不 为 0 的 数 不 超 过 3 个 所有数位上不为0的数不超过3个 03

问 区 间 内 满 足 以 上 条 件 的 数 的 个 数 。 问区间内满足以上条件的数的个数。


题解:

d p [ p o s ] [ c n t ] 表 示 查 找 到 第 p o s 位 , 截 止 当 前 位 的 非 零 数 的 个 数 为 c n t 的 数 的 个 数 。 dp[pos][cnt]表示查找到第pos位,截止当前位的非零数的个数为cnt的数的个数。 dp[pos][cnt]poscnt

  • 记 忆 化 搜 索 , d f s ( p o s − 1 , c n t + ( i = = 0 ? 0 : 1 ) , l e a d & & i = = 0 , l i m i t & & i = = b i t [ p o s ] ) 记忆化搜索,dfs(pos-1, cnt+(i == 0 ? 0 : 1), lead \&\& i == 0, limit \&\& i == bit[pos]) dfs(pos1,cnt+(i==0?0:1),lead&&i==0,limit&&i==bit[pos])

#include <bits\stdc++.h>
using namespace std;
typedef long long ll;
int bit[20];
ll dp[20][1<<7];

ll dfs(int pos, int cnt, bool lead, bool limit){
    if(pos == 0){
        return cnt <= 3;
    }
    if(!limit && !lead && dp[pos][cnt] != -1){
        return dp[pos][cnt];
    }
    int up = (limit ? bit[pos] : 9);
    ll res = 0;
    for(int i = 0 ; i <= up ; i++){
        res += dfs(pos-1, cnt+(i == 0 ? 0 : 1), lead && i == 0, limit && i == bit[pos]);
    }
    if(!limit && !lead){
        dp[pos][cnt] = res;
    }
    return res;
}

ll count(ll x){
    int len = 0;
    while(x){
        bit[++len] = x%10;
        x /= 10;
    }
    return dfs(len, 0, true, true);
}

int main() {
    int t;
    memset(dp, -1, sizeof(dp));
    for(cin >> t ; t > 0 ; t--){
        ll l, r;
        cin >> l >> r;
        cout << count(r)-count(l-1) << endl;
    }
    return 0; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值