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

Beautiful numbers

时间:2017-07-25 22:33:41      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:sub   section   mod   index   upper   hat   amp   main   pos   

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).

Example
Input
1
1 9
Output
9
Input
1
12 15
Output
2

DP好难2333

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;


const int mod=2520;
typedef long long LL;

long long dp[25][mod][50];

int index[2530],bit[25];

void init()
{
    int num=0;
    for(int i=1;i<=mod;i++)
    {
        if(mod%i==0)
            index[i]=num++;
    }
}

int gcd(int a,int b)
{
    if(b==0)return a;
    else return gcd(b,a%b);
}

int lcm(int a,int b)
{
    return a/gcd(a,b)*b;
}

LL dfs(int pos,int presum,int prelcm,bool flag)
{
    if(pos==-1)return presum%prelcm==0;
    if(!flag&&dp[pos][presum][index[prelcm]]!=-1)
        return dp[pos][presum][index[prelcm]];
    LL ans=0;
    int up=flag?bit[pos]:9;
    for(int i=0;i<=up;i++)
    {
        int nowsum=(presum*10+i)%mod;
        int nowlcm=prelcm;
        if(i)nowlcm=lcm(nowlcm,i);
        ans+=dfs(pos-1,nowsum,nowlcm,flag&&i==up);
    }
    if(!flag)dp[pos][presum][index[prelcm]]=ans;
    return ans;
}

LL solve(LL x)
{
    int len=0;
    while(x)
    {
        bit[len++]=x%10;
        x/=10;
    }
    return dfs(len-1,0,1,true);
}

int main()
{
    int T;
    init();
    memset(dp,-1,sizeof(dp));
    scanf("%d",&T);
    while(T--)
    {
        LL r,l;
        scanf("%I64d%I64d",&l,&r);
        printf("%I64d\n",solve(r)-solve(l-1));
    }
    return 0;
}

 

Beautiful numbers

标签:sub   section   mod   index   upper   hat   amp   main   pos   

原文地址:http://www.cnblogs.com/xzxj/p/7236386.html

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