您的位置:首页 > 其它

codeforces--55D--Beautiful numbers(数位dp,dfs+记忆化)

2015-01-21 14:05 387 查看
Beautiful numbers
Time Limit:4000MS     Memory Limit:262144KB     64bit IO Format:%I64d
& %I64u
Submit Status

 

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


题意:给出l,r 求在范围内的数x能乘除lcm(x)的数的个数

先求出1到n内的数的个数。

首先,如果两个数对1到9取余,得到的余数对应相同,那么在这两个数后面加任何相同的数,这两个数对lcm的余数相同。1到9的最小公倍数2520,所以当几个数能对2520取余的结果相同,同时这些数是由相同的数组成的,那么这些数可以分为一类,它们的后面加任何相同的数后,对自身lcm取余,仍然相同。

dp[i][256][2520],代表当前的数有i位时,其中256为状态压缩后的2到9,然后是对2520的取余结果。

由此,进行数位dp

 

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std ;
#define LL __int64
LL dp[20][256][2520] , digit[20] , cnt ;
int f(int k,int mods)
{
int i ;
for(i = 0 ; i <= 7 ; i++)
{
if( k&(1<<i) )
{
if(mods%(i+2) != 0)
break ;
}
}
if( i <= 7 )
return 0 ;
return 1 ;
}
LL dfs(int cnt,int pre,int mods,int maxd,int zero)
{
if( cnt == 0 ) return !mods || ( f(pre,mods) ) ;
if( maxd && zero && dp[cnt][pre][mods] != -1 )
return dp[cnt][pre][mods] ;
LL i , r = maxd ? 9 : digit[cnt] , ans = 0 , k ;
for(i = 0 ; i <= r ; i++)
{
if( i >= 2 && (pre&( 1<<(i-2) ))==0 )
{
ans += dfs(cnt-1,pre|(1<<(i-2)) ,(mods*10+i)%2520,maxd||i<r,zero||i ) ;
}
else
ans += dfs(cnt-1,pre,(mods*10+i)%2520,maxd||i<r,zero||i ) ;
}
if( maxd && zero ) dp[cnt][pre][mods] = ans ;
return ans ;
}
LL solve(LL temp)
{
memset(digit,0,sizeof(digit)) ;
cnt = 0 ;
while( temp )
{
digit[++cnt] = temp%10 ;
temp /= 10 ;
}
return dfs(cnt,0,0,0,0) ;
}
int main()
{
int t ;
LL n , m ;
memset(dp,-1,sizeof(dp)) ;
scanf("%d", &t) ;
while(t--)
{
scanf("%I64d %I64d", &n, &m) ;
printf("%I64d\n", solve(m)-solve(n-1)) ;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: