Beautiful numbers Codeforces Beta Round 51

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.

//大意:
// 一个正整数是美丽的,当且仅当它能被它的每一个非零数字整除时。
//给定一个左右边界,求有多少个美丽数(数据范围1 ≤ li ≤ ri ≤ 9 ·e18)

//*关键点1:2520为1,2,3,4,5,6,7,8,9的最小公倍数,我最开始的时候很不理解这个2520。

//关键点2:通过数组对除数标记,从而减小数组的大小。

#include<stdio.h>
#include<string>
#include<stack>
#include<iostream>
#include<map>
#include<stdlib.h>
#include<cmath>
#include<vector>
#include<algorithm>
#include<string.h>
using namespace std;
typedef long long ll;

int a[20];//long long 20位就够
ll dp[20][2520 + 5][50];//数组要开long long的,不然会wa掉
int mp[2520 + 5];
ll gcd(ll a, ll b)//求最大公约数
{
    if (a < b) { swap(a, b); }
    ll r = 0;
    while (a%b!=0)
    {
        r = a % b;
        a = b;
        b = r;
    }
    return b;
}
/*
  pos:枚举的位数,一般从高位到地位,如果预处理得到的是低位到高位,则需进行逆置
  lcm:当前的最大公约数,每次深搜时要预处理
  lim:当前位的限制(题中要求在区间内)
  sum:前len-pos位的数 % 2520(2520为1,2,3,4,5,6,7,8,9的最小公倍数)
*/
ll dfs(int pos, int lcm, bool lim, int sum)
{
    if (pos == 0)return sum % lcm==0;//所有位枚举完了之后返回
    if (!lim && dp[pos][sum][mp[lcm]] != -1)return dp[pos][sum][mp[lcm]];//若无限制并且当前值已经计算过,那么返回计算过的值即可。
    int up = lim ? a[pos] : 9;//若有限制,则按限制的最大数a[pos]来,不然就从9开始。
    ll res=0;
    for (int i = 0; i <= up; i++)//开始枚举下一位,从0到9,闭区间up别忘了。
    {
        res += dfs(pos - 1, i ? lcm/gcd(lcm, i) * i : lcm, lim && i == up, (sum * 10 + i) % 2520);//中间表达式的意思是判断lcm中是否已经是i的约数了。
    }
    if (!lim)dp[pos][sum][mp[lcm]] = res;//计算结束的赋值,下一次直接调用这个值就行。
    return res;//返回最终值
}
ll solve(ll x)//预处理函数
{
    int len = 0;//枚举数的位数
    while(x)
    {
        a[++len] = x % 10;//++len也可以写成后置++,但后面传参要传len-1并且判断退出条件为 pos==-1。++len这么写简单
        x /= 10;
    }
    //memset(dp, -1, sizeof(dp));对dp数组进行初始化,因为有的结果为0,所以我们初始化成-1更好,一般在初始化函数里初始化数组,但这么写会超时。
    return dfs(len, 1, 1, 0);//进行按位枚举,最高位一般是有限制的,除非最高位是9,故lim为1。
}
int main()
{
    int t;//测试用例数量
    int num = 0;//计数的
    cin >> t;
    memset(dp, -1, sizeof(dp));
    for (int i = 1; i <= 2520; i++)
        if (2520 % i == 0)mp[i] = ++num;//用映射关系来减少dp数组的空间(每个能被除的数对应num的值不同)
    while (t--)
    {
        ll l, r;//左右边界
        cin >> l >> r;
        cout << solve(r) - solve(l - 1) << endl;//右边界减去(左边界-1)即为答案
    }
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值