J Beautiful Numbers(上海大都会赛数位dp)

链接:https://www.nowcoder.com/acm/contest/163/J
来源:牛客网
 

题目描述

NIBGNAUK 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 the sum of its digits.

We will not argue with this and just count the quantity of beautiful numbers from 1 to N.

输入描述:

The first line of the input is T(1≤ T ≤ 100), which stands for the number of test cases you need to solve.
Each test case contains a line with a positive integer N (1 ≤ N ≤ 1012).

输出描述:

For each test case, print the case number and the quantity of beautiful numbers in [1, N].

示例1

输入

复制

2
10
18

输出

复制

Case 1: 10
Case 2: 12

题目为给一个n,让求比n小的数中有多少个数是满足本身能被数位之和整除,这题范围为1e12肯定不能暴力,我们考虑一下数位dp,dp[pos][sum][remain],表示在第pos位,当前的和为sum,remain为当前数的大小,由同余模定理可以知道,在计算中间取模与最后取模是一样的,所以可以每一步对remain取模,然后就是数位dp了,dp过程需要通过dfs来实现。

AC代码:

#include<stdio.h>
#include<iostream>
#include<string.h>
#define mem(a, b) memset(a, b, sizeof(a))
#define IOS ios::sync_with_stdio(false)
using namespace std;
typedef long long LL;
LL dp[13][120][120], a[20];
int mod;

LL dfs(int pos, int sum, int remain, bool limit)
{
    if(pos == -1) return sum==mod&&!remain;
    if(!limit && dp[pos][sum][remain] != -1) return dp[pos][sum][remain];
    int up = limit ? a[pos] : 9;
    LL res = 0;
    for(int i = 0; i <= up; i++)
    {
        if(sum+i > mod) break;
        res += dfs(pos-1, sum+i, (remain*10+i)%mod, limit&&i==a[pos]);
    }
    if(!limit) dp[pos][sum][remain] = res;
    return res;
}

LL solve(LL x)
{
    int pos = 0;
    while(x)
    {
        a[pos++] = x%10;
        x /= 10;
    }
    LL ans = 0;
    for(int i = 1; i <= pos*9; i++)
    {
        mem(dp, -1);
        mod = i;
        ans += dfs(pos-1, 0, 0, 1);
    }
    return ans;
}
int main()
{
    IOS;
    int T, cas = 0;
    cin >> T;
    while(T--)
    {
        mem(a, 0);
        LL n;
        cin >> n;
        cout << "Case " << ++cas << ": " << solve(n) << endl;
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值