2018上海acm————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

题意:题目的意思是给你一个数让你求从1到这个数中的 Beautiful Numbers (能被各个数位上的数字和整除的数  比如 12的各个数位上的和1+2=3,12能被3整除所以12是Beautiful Numbers);

思路:思路就是数位dp--有意思的东西

dp[i][j][k]的意思是i位的数,各个数位上的和为j,k的意思是mod i,其中dfs是从第一位开始枚举,如果一个数比如说2345,这其中的k的意思就是从第一位开始mod i(因为你一开始假设是数位和为 i,所以你要看看这个数能不能被i求mod为0)2345整体求模等于从最高位求模;

#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll mod;
ll n;
ll a[22];  //记录各个位上的值
ll dp[22][109][150];

ll dfs(ll pos,ll num,ll sum,ll lim)  //因为你要从各个位上枚举但是你不能超过给你的n值,这里就需要用lim如果lim为1就说明你选的i的值就是当前位最大
{
    if(pos==-1)                     //如果pos==-1就说明这个数你构造完了
        return num==0&&sum==0;    //num和sum为0就说明你构造的这个数能被整除
    if(!lim&&dp[pos][num][sum]!=-1)
        return dp[pos][num][sum];
    ll fd=lim?a[pos+1]:9;     //如果你选了上一位的最大值那麽这一位就不能超过n的当前位的值
    ll ans=0;
    for(ll i=0; i<=fd; i++)
    {
        if(i>num)
            break;
        else
        {
            ans+=dfs(pos-1,num-i,(sum*10+i)%mod,lim&&i==a[pos+1]);
            // cout<<ans<<endl;
        }
    }
        dp[pos][num][sum]=ans;
    return ans;
}
int main()
{
    ll t,i;
    cin>>t;
    ll x=1;
    while(t--)
    {
        ll na=0;
        scanf("%lld",&n);

        int k=0;
        memset(a,0,sizeof(a));
        while(n)
        {
            a[++k]=n%10;
            n/=10;
        }               //将各个位上的值存入数组
        //cout<<k<<endl;
        for(i=1; i<=k*9; i++)    //位数你知道了各个位数最大你就知道了
        {
            //cout<<i<<endl;
            mod=i;
            memset(dp,-1,sizeof(dp));
            na+= dfs(k-1,i,0,1);
            //cout<<na<<endl;
        }
        printf("Case %lld: %lld\n",x,na);
        x++;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值