首页 > 其他 > 详细

CF 55D 数位dp

时间:2014-02-08 09:47:02      阅读:425      评论:0      收藏:0      [点我收藏+]
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 isbeautiful 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 nextt 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 usecin (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 (fromli tori, inclusively).

Sample test(s)
Input
1
1 9
Output
9
Input
1
12 15
Output
2


题意:给定A,B,求A,B之间所有能被自己每一个非零位整除的数的个数。

乍一看毫无头绪,按直接的方法做,肯定会爆能存,看别人的思路,构造好巧妙,从1到9的最小公倍数是2520,每一个数被自己的非零位整除,则一定为2520的某一个因子整除,因此求和可以直接对2520取模,这样不影响结果,从1到2520,所有的最小公倍数只有48个,因此可以离散化一下,后面就是数位dp的过程了。dp[pos][presum][index[prelcm]]三个参数代表当前位的和,以及从前往后的lcm值,

代码:

/* ***********************************************
Author :xianxingwuguan
Created Time :2014-2-8 0:11:46
File Name :1.cpp
************************************************ */
#pragma comment(linker, "/STACK:102400000,102400000")
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <string>
#include <time.h>
#include <math.h>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
typedef long long ll;
ll dp[30][3000][60],num[30],indexx[3000],cnt;
const ll mod=2520LL;
ll gcd(ll a,ll b){
	if(a==0)return b;
	return gcd(b%a,a);
}
ll lcm(ll a,ll b){
	return a/gcd(a,b)*b;
}
ll dfs(ll pos,ll presum,ll prelcm,bool flag){
	if(pos==0)return presum%prelcm==0;
	if(flag&&dp[pos][presum][indexx[prelcm]]!=-1)
		return dp[pos][presum][indexx[prelcm]];
	ll u=flag?9:num[pos];
	ll ans=0;
	for(ll d=0;d<=u;d++){
		ll newsum=(presum*10+d)%mod;
		ll newlcm=prelcm;
		if(d)newlcm=lcm(d,newlcm);
		ans+=dfs(pos-1,newsum,newlcm,flag||d<u);
	}
	if(flag)dp[pos][presum][indexx[prelcm]]=ans;
	return ans;
}
ll solve(ll x){
	ll len=0;
	while(x){
		num[++len]=x%10;
		x/=10;
	}
	//cout<<"hahah"<<endl;
	return dfs(len,0,1,0);
}
int main(){
	ll T,A,B;
	cnt=0;
	for(ll i=1;i<=mod;i++)
		if(mod%i==0)
			indexx[i]=cnt++;
	memset(dp,-1,sizeof(dp));
	 cin>>T;
	 while(T--){
		 cin>>A>>B;
		 //cout<<"hahah"<<endl;
		 cout<<solve(B)-solve(A-1)<<endl;
	 }

}



CF 55D 数位dp

原文:http://blog.csdn.net/xianxingwuguan1/article/details/18977249

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!