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

题目链接: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;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值