codeforces--55D--Beautiful numbers(数位dp,dfs+记忆化)

Beautiful numbers
Time Limit:4000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u

 

Description

Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits. We will not argue with this and just count the quantity of beautiful numbers in given ranges.

Input

The first line of the input contains the number of cases t (1 ≤ t ≤ 10). Each of the next t lines contains two natural numbers li and ri (1 ≤ li ≤ ri ≤ 9 ·1018).

Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).

Output

Output should contain t numbers — answers to the queries, one number per line — quantities of beautiful numbers in given intervals (from li to ri, inclusively).

Sample Input

Input
1
1 9
Output
9
Input
1
12 15
Output
2

题意:给出l,r 求在范围内的数x能乘除lcm(x)的数的个数

先求出1到n内的数的个数。

首先,如果两个数对1到9取余,得到的余数对应相同,那么在这两个数后面加任何相同的数,这两个数对lcm的余数相同。1到9的最小公倍数2520,所以当几个数能对2520取余的结果相同,同时这些数是由相同的数组成的,那么这些数可以分为一类,它们的后面加任何相同的数后,对自身lcm取余,仍然相同。

dp[i][256][2520],代表当前的数有i位时,其中256为状态压缩后的2到9,然后是对2520的取余结果。

由此,进行数位dp

 

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std ;
#define LL __int64
LL dp[20][256][2520] , digit[20] , cnt ;
int f(int k,int mods)
{
    int i ;
    for(i = 0 ; i <= 7 ; i++)
    {
        if( k&(1<<i) )
        {
            if(mods%(i+2) != 0)
                break ;
        }
    }
    if( i <= 7 )
        return 0 ;
    return 1 ;
}
LL dfs(int cnt,int pre,int mods,int maxd,int zero)
{
    if( cnt == 0 ) return !mods || ( f(pre,mods) ) ;
    if( maxd && zero && dp[cnt][pre][mods] != -1 )
        return dp[cnt][pre][mods] ;
    LL i , r = maxd ? 9 : digit[cnt] , ans = 0 , k ;
    for(i = 0 ; i <= r ; i++)
    {
        if( i >= 2 && (pre&( 1<<(i-2) ))==0 )
        {
            ans += dfs(cnt-1,pre|(1<<(i-2)) ,(mods*10+i)%2520,maxd||i<r,zero||i ) ;
        }
        else
            ans += dfs(cnt-1,pre,(mods*10+i)%2520,maxd||i<r,zero||i ) ;
    }
    if( maxd && zero ) dp[cnt][pre][mods] = ans ;
    return ans ;
}
LL solve(LL temp)
{
    memset(digit,0,sizeof(digit)) ;
    cnt = 0 ;
    while( temp )
    {
        digit[++cnt] = temp%10 ;
        temp /= 10 ;
    }
    return dfs(cnt,0,0,0,0) ;
}
int main()
{
    int t ;
    LL n , m ;
    memset(dp,-1,sizeof(dp)) ;
    scanf("%d", &t) ;
    while(t--)
    {
        scanf("%I64d %I64d", &n, &m) ;
        printf("%I64d\n", solve(m)-solve(n-1)) ;
    }
    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值