CodeForces - 55D——Beautiful numbers (数位dp)

题目链接:http://codeforces.com/problemset/problem/55/D

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
Copy
1
1 9
Output
Copy
9
Input
Copy
1
12 15
Output
Copy
2

思路:一道数位dp的经典题,可是刚学数位dp的我太弱了,做不出来。。。

参考了别人的思路后明白了这道题的做法,还是有很大收获的。

#include<cstring>
#include<iostream>
#include<cstdio>
#define mod 2520
typedef long long ll;
using namespace std; 
ll dp[20][2550][60];
ll gcd(ll a, ll b){  
    return b?gcd(b,a%b):a;  
}  
ll lcm(ll a,ll b){
    return a/gcd(a,b)*b;
}
int Hash[2550];
void init(){
    int cnt=0;
    for(int i=1;i<=mod;i++){
        if(mod%i==0){
            Hash[i]=++cnt;
        }
    }
} 
int a[30];  
ll dfs(int pos,int premod,int prelcm,bool limit) 
{    
    if(pos==-1) return premod%prelcm==0;  
    if(!limit && dp[pos][premod][Hash[prelcm]]!=-1) return dp[pos][premod][Hash[prelcm]];  
    int up=limit?a[pos]:9;
    ll ans=0;  
    for(int i=0;i<=up;i++)
    {  
        int nextmod=(premod*10+i)%mod;
        int nextlcm=prelcm;
        if(i)
        nextlcm=lcm(prelcm,i);
        ans+=dfs(pos-1,nextmod,nextlcm,limit && i==a[pos]) ;
    }   
    if(!limit) dp[pos][premod][Hash[prelcm]]=ans;  
    return ans;  
}  
ll solve(ll x)  
{  
    int pos=0;  
    while(x)
    {  
        a[pos++]=x%10;
        x/=10;  
    }  
    return dfs(pos-1,0,1,true);
}  
int main()  
{  
    ll t;
	ll le,ri;
	scanf("%lld",&t); 
	init();
	memset(dp,-1,sizeof(dp));
    while(t--)  
    {  
        scanf("%lld%lld",&le,&ri);
        printf("%lld\n",solve(ri)-solve(le-1)); 
    }
	return 0;  
}  

猜你喜欢

转载自blog.csdn.net/star_moon0309/article/details/80385584