码迷,mamicode.com
首页 > 其他好文 > 详细

cf Beautiful numbers(数位dp)

时间:2015-04-22 18:32:11      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:cf beautiful number   数位dp   

Beautiful numbers
Time Limit:4000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u

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

题意:求区间内能整除自己每位数(0除外)的个数。

code:

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cmath>
#define ll long long
#define Mod 2520  ////1-9的最小公倍数

using namespace std;

ll l,r;
ll dp[30][Mod][50];///dp[i][j][k] i:长度  j:各个位数最小公倍数对Mod取摸  k:最小公倍数对应的值得离散下标
int num[30];
int b[Mod+1];     ///记录最小公倍数

ll gcd(ll a,ll b) {
    return b==0?a:gcd(b,a%b);
}

ll Lcm(ll a,ll b) {
    return a/gcd(a,b)*b;
}

ll dfs(int i,ll lcm,ll sum,bool e) {
    if(i<=0)return sum%lcm==0;
    if(!e&&dp[i][sum][b[lcm]]!=-1)return dp[i][sum][b[lcm]];
    ll res=0;
    int u=e?num[i]:9;
    for(ll d=0; d<=u; d++) {
        if(d==0)                 ///d==0时,lcm不变
            res+=dfs(i-1,lcm,sum*10%Mod,e&&d==u);
        else
            res+=dfs(i-1,lcm*d/gcd(lcm,d),(sum*10+d)%Mod,e&&d==u);
    }
    return e?res:dp[i][sum][b[lcm]]=res;
}
 
ll solve(ll n) {
    int len=1;
    while(n) {
        num[len++]=n%10;
        n/=10;
    }
    return dfs(len-1,1,0,1);
}

int main() {
    memset(dp,-1,sizeof dp);
    int cnt=0;
    ///离散记录lcm值
    for(int i=1; i<=Mod; i++)if(Mod%i==0)b[i]=cnt++;
    int t;
    scanf("%d",&t);
    while(t--) {
        scanf("%I64d%I64d",&l,&r);
        ll ans=solve(r)-solve(l-1);
        printf("%I64d\n",ans);
    }
    return 0;
}

cf Beautiful numbers(数位dp)

标签:cf beautiful number   数位dp   

原文地址:http://blog.csdn.net/acm_baihuzi/article/details/45195769

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!