Beautiful Numbers(牛客网)

链接:https://ac.nowcoder.com/acm/problem/17385
来源:牛客网

题目描述

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 ≤ 1e12)

输出描述:

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:
 

题意:给你一个数n让你判断在1-n中有多少个数求余它每个位上的数字之和为0
题解:
由于给的数字较大,暴力跑肯定会超时,就想到用数位dp去做,因为最大范围是1e12,则每个位上的数之和一定不大于12*9=108,则求出范围内各个数上和的最大值x,再从1枚举到x,进行数位dp.

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int num[20];
ll dp[15][120][120];
int too;
ll dfs(int pos,int mod,int sum,bool limit)
{
    if(pos==-1)
        return mod==0&&sum==too;
    if(!limit&&dp[pos][mod][sum]!=-1)
        return dp[pos][mod][sum];
    int mx=limit?num[pos]:9;
    ll ans=0;
    for(int i = 0;i <= mx;++i)
    {
        if(sum+i<=too)
        ans+=dfs(pos-1,(mod*10+i)%too,sum+i,limit&&i==mx);
    }
    if(!limit)
        dp[pos][mod][sum]=ans;
    return ans;
}
ll solve(ll x)
{
    int d=0;
    int ret=0;
    while(x)
    {
        int temp=x%10;
        num[d++]=temp;
        x/=10;
        ret+=temp;
    }
    int nx=num[d-1]-1+(d-1)*9;
    ret=max(ret,nx);
    ll ans=0;
    for(int i = 1;i <= ret;++i)
    {
        memset(dp,-1,sizeof(dp));
        too=i;
        ans+=dfs(d-1,0,0,1);
    }
    return ans;
}
int main()
{
    int t;
    scanf("%d",&t);
    int res=0;
    while(t--)
    {
        ll a;
        res++;
        scanf("%lld",&a);
        ll ans=solve(a);
        printf("Case %d: ",res);
        printf("%lld\n",ans);
    }
    return 0;
}

  

 

转载于:https://www.cnblogs.com/aaddvvaanntteezz/p/10695685.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值