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;
}

猜你喜欢

转载自blog.csdn.net/MALONG11124/article/details/81459442
今日推荐