数位DP(离散化+技巧)

题目链接

从1到9的最小公倍数是2520,每一个数被自己的非零位整除,则一定为2520的某一个因子整除,因此求和可以直接对2520取模,这样不影响结果,从1到2520,所有的最小公倍数只有48个,因此可以离散化一下,后面就是数位dp的过程了。dp[pos][presum][index[prelcm]]表示到了第几位,到目前为止和为多少,到目前为止的lcm值。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<string>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f;
const int mod=2520;
int cnt;
int a[100];
int b[2520];
ll dp[60][2520][60];
int f(int a,int b){return a*b/(__gcd(a,b));}
ll dfs(int pos,int presum,int prelcm,int flag)
{
    if(pos==0) return presum%prelcm==0;
    if(!flag&&dp[pos][presum][b[prelcm]]!=-1)
        return dp[pos][presum][b[prelcm]];
    int up=flag?a[pos]:9;
    ll ans=0;
    for(int i=0;i<=up;i++)
    {
        int sum=(presum*10+i)%mod;
        int lcm=prelcm;
        if(i) lcm=f(i,lcm);
        ans+=dfs(pos-1,sum,lcm,flag&&i==up);
    }
    if(!flag)dp[pos][presum][b[prelcm]]=ans;
    return ans;
}
ll solve(ll x)
{
    int pos=0;
    while(x)
    {
        a[++pos]=x%10;
        x/=10;
    }
    return dfs(pos,0,1,1);
}
int main()
{
    cnt=0;memset(dp,-1,sizeof(dp));
    for(int i=1;i<=mod;i++)if(mod%i==0)b[i]=cnt++;
    int t;scanf("%d",&t);
    while(t--)
    {
        ll l,r;scanf("%lld%lld",&l,&r);
        printf("%lld\n",solve(r)-solve(l-1));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值