Codeforces Beta Round #51 D. Beautiful numbers 数位dp

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
1
1 9
output
9
input
1
12 15
output
2

 题意:美丽数定义:一个数可以整除它每一位数;问区间内有多少美丽数;

思路:

  发现1.。。。9的lcm为2520

  数位dp

   dp[i][j][k]表示第i位i位数的lcm,余2520的余数的个数;

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<queue>
#include<algorithm>
#include<stack>
#include<cstring>
#include<vector>
#include<list>
#include<set>
#include<map>
using namespace std;
#define ll long long
#define pi (4*atan(1.0))
#define eps 1e-4
#define bug(x)  cout<<"bug"<<x<<endl;
const int N=1e2+10,M=1e6+10,inf=2147483647;
const ll INF=1e18+10,mod=1e7+7;
ll bit[N],flag[M];
ll f[N][60][2530];
void init()
{
    int s=1;
    for(int i=1;i<=2520;i++)
        if(2520%i==0)
        flag[i]=s++;
}
ll dp(int pos,int fl,ll m,ll sum)
{
    if(pos==0)return (m%sum==0);
    if(fl&&f[pos][flag[sum]][m]!=-1)return f[pos][flag[sum]][m];
    ll x=fl?9:bit[pos];
    ll ans=0;
    for(ll i=0;i<=x;i++)
    {
        if(i)
            ans+=dp(pos-1,fl||i<x,(m*10+i)%2520,(sum*i)/__gcd(sum,i));
        else
            ans+=dp(pos-1,fl||i<x,(m*10+i)%2520,sum);
    }
    if(fl)f[pos][flag[sum]][m]=ans;
    return ans;
}
ll getans(ll x)
{
    int len=0;
    while(x)
    {
        bit[++len]=x%10;
        x/=10;
    }
    return dp(len,0,0,1);
}
int main()
{
    init();
    int T;
    scanf("%d",&T);
    memset(f,-1,sizeof(f));
    while(T--)
    {
        ll l,r;
        scanf("%lld%lld",&l,&r);
        //cout<<getans(r)<<" "<<getans(l)<<endl;
        printf("%lld
",getans(r)-getans(l-1));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jhz033/p/6589519.html