您的位置:首页 > 其它

【数位dp】Beautiful numbers CodeForces - 55D

2017-05-21 10:34 253 查看
Beautiful numbers  CodeForces - 55D

碰到的第二类数位dp的问题:求被整除的个数

这一种不同的特征在于余数,所以将余数作为dp的变量。

这题比较麻烦,题意简单的来说是:找(非0)的所有位数都能整除这个数的数。

要使所有非0位数整除这个数,那么 这个数%这些非0位数的最小公倍数==0。

那么不同的特征不仅在余数,还有最小公倍数上。

因为最小公倍数最大是2520,那么余数最大也就是2520,那么要开dp[20][2520][2520],会爆内存。

发现0-9之间最小公倍数只有48个,那么离散化下,则开个dp[20][2520][50]即可。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<map>
#include<queue>
#include<cmath>
#include<algorithm>
#include<deque>
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
const int N = 20;
const double eps = 1e-6;
#pragma comment(linker, "/STACK:102400000,102400000")

map<int,int> mp;
int all[1<<10],cut[50];
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;
}
void init() //离散化所有公倍数
{
int cnt = 0;
for(int i = 1; i < (1 << 10); i++)
{
int ans = 1;
for(int j = 1; j < 10; j++)
{
if((1<<j) & i)
ans = lcm(ans,j);
}
if(!mp.count(ans))
{
mp[ans] = cnt;
cut[cnt++] = ans;
}
all[i] = mp[ans];
}
}
char bit
;
LL dp
[2520][50]; // 余数<2520 公约数个数<50
LL dfs(int pos,int res,int state,int limit)
{
if(pos == 0)
{
if(cut[all[state]] == 0)   return 0;
else return res%cut[all[state]] == 0;
}
if(!limit && dp[pos][res][all[state]] != -1 && cut[all[state]] != 0)
return dp[pos][res][all[state]];
int up = limit ? bit[pos]:9;
LL ans = 0;
for(int i = 0; i <= up; i++)
ans += dfs(pos-1,(res*10+i)%2520,state|(1<<i),limit && (i == bit[pos]));
if(!limit && cut[all[state]] != 0)  dp[pos][res][all[state]] = ans;
return ans;
}
LL solve(LL a)
{
int pos = 0;
while(a)
{
bit[++pos] = a%10;
a /= 10;
}
return dfs(pos,0,0,1);
}
int main()
{
int T;
scanf("%d",&T);
init();
memset(dp,-1,sizeof(dp));
while(T--)
{
LL a,b;
scanf("%lld%lld",&a,&b);
printf("%lld\n",solve(b)-solve(a-1));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: