数位dp入门(不含49)

 

给一个数字n,范围在1~2^63-1,求1~n之间含有49的数字有多少个。

思想:总数-不含49的数;

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>

#prag\
ma GCC optimize("O3")

using namespace std;

typedef long long LL;

typedef unsigned long long uLL;

#define REP(i, a, b) for(register LL i = (a), i##_end_ = (b); i <= i##_end_; ++ i)
#define DREP(i, a, b) for(register LL i = (a), i##_end_ = (b); i >= i##_end_; -- i)
#define mem(a, b) memset((a), b, sizeof(a))

template<typename T> inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; }
template<typename T> inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; }

LL read()
{
    register LL sum = 0,fg = 0;char c = getchar();
    while(c < '0' || c > '9') { fg |= c == '-'; c = getchar(); }
    while(c >= '0' && c <= '9') { sum = sum * 10 + c - '0'; c = getchar(); }
    return fg ? -sum : sum;
}

const LL inf = 1e9;
const LL maxn = 100000;

LL T,a[maxn],num;
LL dp[maxn][2];

LL dfs(int pos,int pre,bool lim)
{
    bool flag = (pre == 4);//也可以把flag作为函数参数;
    if(pos == 0)return 1;
    if(!lim && dp[pos][flag]!=-1)return dp[pos][flag];
    int up = lim ? a[pos] : 9;//判断上限
    LL res = 0;
    REP(i,0,up)
    {
        if(pre == 4 && i == 9)continue;//不符条件
        res += dfs(pos-1,i,lim && i == a[pos]);
    }
    if(!lim) dp[pos][flag] = res;
    return res;
}

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

int main()
{
    T = read();
    mem(dp,-1);
    while(T--)
    {
        LL x = read();
        cout<<solve(x)+1<<endl;
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值