CodeForces 55D Beautiful numbers(数位dp+离散化)

题目:求一个区间内的Beautiful numbers有多少个。Beautiful numbers指:一个数能整除所有组成它的非0数字。 
例如15可以被1和5整除,所以15是Beautiful numbers。

好久没写数位dp了,拿过一个来果断卡住了。。。求一下1...9的lcm,对1...lcm的能作为lcm因数的数标号hash,作为一个递归的关键字,然后不断对lcm取模的sum作为第二个关键字,然后递归就可以了,记得把memset(dp)放到外面,否则会TLE。

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
ll A,B,dp[22][55][2600];
int wei[22],has[2600],LCM;
ll dfs(int pos,int sum,int lcm,int limit)
{
    if(pos<1)
        return sum%lcm==0;
    if(!limit&&dp[pos][has[lcm]][sum]>=0)
        return dp[pos][has[lcm]][sum];
    int up=limit?wei[pos]:9;
    ll ans=0;
    for(int i=0;i<=up;i++)
    {
        if(i!=0)
            ans+=dfs(pos-1,(sum*10+i)%LCM,lcm*i/(__gcd(lcm,i)),limit&&i==up);
        else
            ans+=dfs(pos-1,(sum*10+i)%LCM,lcm,limit&&i==up);
    }
    if(!limit) dp[pos][has[lcm]][sum]=ans;
    return ans;
}
ll solve(ll x)
{
    int len=0;
    while(x)
    {
        wei[++len]=x%10;
        x/=10;
    }
    ll ans=dfs(len,0,1,1);
    return ans;

}
void init()
{
    LCM=1;
    for(int i=2;i<=9;i++)
        LCM=LCM*i/__gcd(LCM,i);
    int tot=0;
    for(int i=1;i<=LCM;i++)//少但是很零散不离散一下没法存
    if(LCM%i==0)//
        has[i]=tot++;
    memset(dp,-1,sizeof dp);///
}
int t;
int main()
{
    init();
    //freopen("in.txt","r",stdin);
    scanf("%d",&t);
    while(t--)
    {
        scanf("%I64d%I64d",&A,&B);
        ll ans=solve(B)-solve(A-1);
        printf("%I64d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/dllpXFire/article/details/81158306