@2018 ACM 国际大学生程序设计竞赛上海大都会赛重现赛: J Beautiful Numbers (数位DP)

版权声明:岂曰无衣,与子同袍 https://blog.csdn.net/sizaif/article/details/81583906

题目链接:https://www.nowcoder.com/acm/contest/163/J

链接: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 ≤ 10^12).

输出描述:

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

[题意]

求解: 0-n 内 满足 其位数和%n = 0. 的个数

[思路]

采用数位DP,  最大12 为 也就是12*9个位.  dp[位][位数和][枚举余数] 

然后, 我们在dfs时可以采用  位数和减法的思想,  当 位数和 减到0, 并且余数 是0 时 , 是满足答案的.

具体就可以看代码:

#include <iostream>
#include <bits/stdc++.h>

#define rep(i,a,n) for(int  i=a;i<=n;i++)
#define per(i,a,n) for(int i = n;i>=a;i--)
#define Si(x) scanf("%d",&x)

typedef long long ll;
const int MAXN =1e5+10;

using namespace std;

ll dp[30][150][150];
int a[50];
int mod;
int cot;
ll dfs(int pos,int sum,int re,int lim)
{
    if(pos ==-1)
        return sum==0&&re==0; // 位数和减法的思想  
    if(!lim&&dp[pos][sum][re]!=-1)
        return dp[pos][sum][re];
    int to;
    
    to = lim?a[pos]:9;
    ll ans = 0;
    for(int i = 0;i<=to;i++)
    {
        ////////////
        if(i>sum) break;
        else
            ans += dfs(pos-1,sum-i,(re*10+i)%mod,lim&&i==a[pos]);
        ///////////
    }
    if( !lim)
        dp[pos][sum][re] = ans;
    return ans;
}
int main()
{
    int t;
    Si(t);
    int c= 0;
    while(t--)
    {
        ll n;
        scanf("%lld",&n);
        cot = 0;
        ll te = n;
        while(te)
        {
            a[cot++] = te%10;
            te/=10;
        }
        ll ans = 0;
        rep(i,1,9*cot)
        {
            mod = i;
            memset(dp,-1,sizeof(dp));
            ans += dfs(cot-1,i,0,1);
        }
        printf("Case %d: %lld\n",++c,ans);

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sizaif/article/details/81583906
今日推荐