CodeForces 55D Beautiful numbers (数位DP+状态简化,5级)

J - Beautiful numbers
Crawling in process... Crawling failed Time Limit:4000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u
Appoint description:

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

思路:很容易能想到三维DP dp[第几位][模上最小公倍数数的余数][最小公倍数]

          最小公倍数到2520 为止 ,故 需要 19x2520x2520 爆空间了。

         但实际上能取到的最小公倍数没有2520个,只要几十个,因此可以哈希一下,因为DP只要记录其不同状态就可以了。

        dp不需要每个数都算原因是不同数的mod数不同。因此不会错

         接下来,就是水数位DP了。

     

#include<iostream>
#include<cstring>
#include<cstdio>
#define FOR(i,a,b) for(int i=a;i<=b;++i)
#define clr(f,z) memset(f,z,sizeof(f))
typedef long long LL;
using namespace std;
LL dp[22][2521][50];
const int MOD=2520;
int bit[22];
int gcd(int a,int b)
{ int z;
  while(b)
  {
    z=b;b=a%b;a=z;
  }
  return a;
}
int LCM(int a,int b)
{
  return a*b/gcd(a,b);
}
int to[2521];
void data()
{ int pos=0;
  FOR(i,1,2520)
  if(MOD%i==0)//有可能是因子的,离散做状态
  {
    to[i]=pos++;
  }
}
LL DP(int pp,int mod,int lcm,bool big)
{
  if(pp==0)return mod%lcm==0;
  if(big&&dp[pp][mod][to[lcm]]!=-1)return dp[pp][mod][ to[lcm] ];
  int kn=big?9:bit[pp];
  LL ret=0;
  FOR(i,0,kn)
  { int zlcm;
    if(i==0)zlcm=lcm;
    else zlcm=LCM(lcm,i);
    ret+=DP(pp-1,(mod*10+i)%MOD,zlcm,big||kn!=i);
  }
  if(big)dp[pp][mod][to[lcm]]=ret;
  return ret;
}
LL get(LL x)
{
  int pos=0;
  while(x)
  {
    bit[++pos]=x%10;
    x/=10;
  }
  return DP(pos,0,1,0);
}
int main()
{
  LL x,y;data();clr(dp,-1);
  int n;
  cin>>n;
  while(n--)
  { cin>>x>>y;
    cout<<get(y)-get(x-1)<<"\n";
  }
}



posted @ 2013-08-28 14:52  剑不飞  阅读(180)  评论(0编辑  收藏  举报