CF 55D - Beautiful numbers(数位DP)

Beautiful numbersCrawling in process... Crawling failed Time Limit:4000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u

Submit Status

Description

 

Input

 

Output

 

Sample Input

 

Sample Output

 

Hint

 

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
 
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#define mod 2520
using namespace std;
long long l,r;
long long dp[20][1<<8][2520];//dp[len][mark][num]表示搜到第len位,用来模的数十mark,得到余数num
/* 这里dp数组的第二位压缩的非常巧妙,本来应该开1<<10这么大的,但是实际上只开了1<<8因为0~9中0 1 是所有数的因子,所以只需要讨论i是不是小于2的情况就可以了*/
long long bit[20];//盛放各各位上的数
long long dfs(int len,int mark,int num,bool fp)//搜索到第len位,取得数十mark。余数是num,,是不是受限制
{
    if(len<1)
    {
        for(int i=0;i<8;i++)
            if((mark&(1<<i))&&num%(i+2)!=0)
                return 0;
        return 1;
    }
    if(!fp&&dp[len][mark][num]!=-1)
        return dp[len][mark][num];
    long long cur=0;
    int fmax=fp?bit[len]:9;
    for(int i=0;i<=fmax;i++)
        cur+=dfs(len-1,i<2?mark:mark|(1<<(i-2)),(num*10+i)%mod,fp&&i==fmax);
    if(!fp)
        dp[len][mark][num]=cur;
    return cur;
}
long long solve(long long n)
{
    int len=0;
    while(n)
    {
        bit[++len]=n%10;
        n/=10;
    }
    return dfs(len,0,0,true);
}
int main()
{
    //freopen("in.txt","r",stdin);
    int t;
    memset(dp,-1,sizeof dp);
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lld%lld",&l,&r);
        printf("%lld\n",solve(r)-solve(l-1));
    }
    return 0;
}

 

posted @ 2016-08-12 13:45  勿忘初心0924  阅读(149)  评论(0编辑  收藏  举报