Codeforces Beta Round #51 D. Beautiful numbers

来源:互联网 发布:python爬虫网页数据 编辑:程序博客网 时间:2024/05/29 11:45
D. Beautiful numbers
time limit per test
4 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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 test(s)
input
11 9
output
9
input
112 15
output
2
数位dp,这题,要求最后的数,对于,每一个数字都要整除,那么,我们就可以通过,一个数能整除所有数字的最小公倍数就可以了!所以我们用dp[i][j][]表示第i位,最小公倍数为j,第i位时余下的是k时的最后的个数,这题还可以进行优化,最是把最小公倍数编号,因为,2-9最小公倍数最大是2520,也就是说,只有48个,这样,大大节省了内存,加快速度!
#include <iostream>#include <stdio.h>#include <string.h>using namespace std;#define M 23__int64 dp[M][55][3500],pri[M];int hash[3500],kk=0;int gcd(int a,int b){    if(a==0)return b;    return gcd(b%a,a);}int get(int t,int i){    if(i==0||i==1)return t;    return t*i/gcd(t,i);}__int64 dfs(int pos,int t,int flag,int pre){    if(pos==0)return pre%t==0;    if(!flag&&dp[pos][hash[t]][pre]!=-1)return dp[pos][hash[t]][pre];    int u=flag?pri[pos]:9;    __int64 ans=0;    for(int i=0;i<=u;i++)    ans+=dfs(pos-1,get(t,i),flag&&i==u,(pre*10+i)%2520);    return flag?ans:dp[pos][hash[t]][pre]=ans;}__int64 solve(__int64 x){    int cnt=0;    while(x){        pri[++cnt]=x%10;x/=10;    }    return dfs(cnt,1,1,0);}int init(){    memset(dp,-1,sizeof(dp));    int cnt=0;    hash[0]=0;    for(int i=1;i<=8;i*=2)        for(int j=1;j<=9;j*=3)            for(int k=1;k<=5;k*=5)                for(int x=1;x<=7;x*=7)                hash[i*j*k*x]=++cnt;}int main(){    int tcase;__int64 n,m;    init();    while(scanf("%d",&tcase)!=EOF){        while(tcase--){            scanf("%I64d%I64d",&m,&n);            printf("%I64d\n",solve(n)-solve(m-1));        }    }    return 0;}


原创粉丝点击