codeforces 55D D. Beautiful numbers(数位dp+数论)

35 篇文章 0 订阅
19 篇文章 0 订阅

题目传送门:
codeforce 55D
题意简单就不说了
思路:
要用到数论的知识。详细解释,推荐一个网址:传送门
注意hash的方式有很多种。hash的目的是为减少空间浪费了。
话不多说,上代码。

AC code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
//#define LOCAL
using namespace std;
typedef long long LL;

LL dp[20][2530][60];//定义状态dp[i][j][k]代表i位在任意组合下得到的所有数位的数字的最小公倍数为j
//的每个数位上的数字之积%2520为k的方案数。
int d[20],hush[2530];
LL GCD( LL x,LL y ){//递归,辗转相除法 
    if(y == 0){
        return x;
    }
    return GCD(y,x%y);
} 
LL LCM(LL x,LL y){
    //return x * y / GCD(x,y);
    return x / GCD(x,y) * y;//先除再乘,防止溢出 
}
LL dfs(int pos,LL mod,LL lcm,bool uplimited){
    if(pos <= 0){
        return (mod % lcm) == 0;
    }
    if(!uplimited && dp[pos][mod][hush[lcm] ] != -1){
        return dp[pos][mod][hush[lcm] ];
    }
    LL temp = 0;
    int up = uplimited ? d[pos] : 9;
    for(int i = 0;i <= up;++i){
        LL mod_t = (mod * 10 + i ) % 2520;
        LL lcm_t = (i == 0) ? lcm : LCM(i,lcm);
        temp += dfs(pos - 1,mod_t,lcm_t, uplimited && i == d[pos]);
    } 
    if(!uplimited){
        dp[pos][mod][hush[lcm] ] = temp;
    }
    return temp;
}
LL solve(LL x){
    LL temp = x;
    int cnt = 0;
    while(temp > 0){
        d[++cnt] = temp % 10;
        temp /= 10;
    }
    d[cnt+1] = 0;
    return dfs(cnt,0,1,true);
}
void init(){
    memset(dp,-1,sizeof(dp));
    int a = 0;
    for(int i = 1;i * i< 2520;++i){//对2520的因子进行hush储存(压缩) 
        if(2520 % i == 0){
            hush[i] = a++;
            hush[2520/i] = a++;
        }
    }

}
int main(){
    #ifdef LOCAL
        freopen("a.txt","r",stdin);
    #endif
    int T = 0;
    LL l = 0,r = 0; 
    cin >> T;
    init();
    while(T--){
        cin >> l >> r;
        cout << solve(r) - solve(l - 1) << endl;
    }
    return 0;
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值