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