codeforce 55 D. Beautiful numbers(数位dp,好题)

来源:互联网 发布:excel表格怎么填充数据 编辑:程序博客网 时间:2024/05/22 06:48

题目链接
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).

Examples
input
11 9
output
9
input
112 15
output
2

题意:

一个美丽数就是可以被它的每一位的数字整除的数。给定一个区间,求美丽数的个数。


题解:

传送门


#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>#include<vector>using namespace std;typedef long long ll;const int MOD=2520;ll d[20][MOD][50];int H[MOD],bit[20];int cnt=0;int gcd(int a,int b){return b==0? a:gcd(b,a%b);}int lcm(int a,int b){return a/gcd(a,b)*b;}void init(){cnt=0;for(int i=1;i<=MOD;i++) if(MOD%i==0) H[i]=++cnt;}ll dp(int pos,int mod,int l,int f){if(pos==-1) return (mod%l==0);if(!f&&d[pos][mod][H[l]]!=-1) return d[pos][mod][H[l]];ll ans=0;int end=f? bit[pos]:9;ans+=dp(pos-1,mod*10%MOD,l,f&&(bit[pos]==0));for(int i=1;i<=end;i++)ans+=dp(pos-1,(mod*10+i)%MOD,lcm(l,i),f&&(i==end));if(!f) d[pos][mod][H[l]]=ans;return ans;}ll cal(ll x){int num=0;while(x){bit[num++]=x%10;x/=10;}return dp(num-1,0,1,1);}int main(){int cas;scanf("%d",&cas);memset(d,-1,sizeof(d));init();while(cas--){ll a,b;scanf("%I64d%I64d",&a,&b);printf("%I64d\n",cal(b)-cal(a-1));}return 0;}

0 0