【数位dp】Beautiful numbers CodeForces - 55D

Beautiful numbers  CodeForces - 55D

碰到的第二类数位dp的问题:求被整除的个数

这一种不同的特征在于余数,所以将余数作为dp的变量。

这题比较麻烦,题意简单的来说是:找(非0)的所有位数都能整除这个数的数。

要使所有非0位数整除这个数,那么 这个数%这些非0位数的最小公倍数==0。

那么不同的特征不仅在余数,还有最小公倍数上。

因为最小公倍数最大是2520,那么余数最大也就是2520,那么要开dp[20][2520][2520],会爆内存。

发现0-9之间最小公倍数只有48个,那么离散化下,则开个dp[20][2520][50]即可。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<map>
#include<queue>
#include<cmath>
#include<algorithm>
#include<deque>
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
const int N = 20;
const double eps = 1e-6;
#pragma comment(linker, "/STACK:102400000,102400000")

map<int,int> mp;
int all[1<<10],cut[50];
LL gcd(LL a,LL b) {
    return b==0 ? a:gcd(b,a%b);
}
LL lcm(LL a,LL b){
    return a/gcd(a,b)*b;
}
void init() //离散化所有公倍数
{
    int cnt = 0;
    for(int i = 1; i < (1 << 10); i++)
    {
        int ans = 1;
        for(int j = 1; j < 10; j++)
        {
            if((1<<j) & i)
               ans = lcm(ans,j);
        }
        if(!mp.count(ans))
        {
            mp[ans] = cnt;
            cut[cnt++] = ans;
        }
        all[i] = mp[ans];
    }
}
char bit[N];
LL dp[N][2520][50]; // 余数<2520 公约数个数<50
LL dfs(int pos,int res,int state,int limit)
{
    if(pos == 0)
    {
        if(cut[all[state]] == 0)   return 0;
        else return res%cut[all[state]] == 0;
    }
    if(!limit && dp[pos][res][all[state]] != -1 && cut[all[state]] != 0)
        return dp[pos][res][all[state]];
    int up = limit ? bit[pos]:9;
    LL ans = 0;
    for(int i = 0; i <= up; i++)
        ans += dfs(pos-1,(res*10+i)%2520,state|(1<<i),limit && (i == bit[pos]));
    if(!limit && cut[all[state]] != 0)  dp[pos][res][all[state]] = ans;
    return ans;
}
LL solve(LL a)
{
    int pos = 0;
    while(a)
    {
        bit[++pos] = a%10;
        a /= 10;
    }
    return dfs(pos,0,0,1);
}
int main()
{
    int T;
    scanf("%d",&T);
    init();
    memset(dp,-1,sizeof(dp));
    while(T--)
    {
        LL a,b;
        scanf("%lld%lld",&a,&b);
        printf("%lld\n",solve(b)-solve(a-1));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值