链接: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
分析:题意是给出一个n,然后求出1-n中有几个数每个位置上的数相加刚好是那个数的倍数。(如12,个位数是2,十位数是1,相加是3,3 刚好是12的倍数)。理解完题意之后就会发现这是一道裸的数位dp,定义dp[i][j][k](i是当前到第几位,j是各个位置相加的和,k是指当前数模上某一个数mod后的值),当pos == -1以后,若sum(即j)==mod && res(即k)==0, 则这一个数满足条件,结果加一,其他的套公式即可。 如果不了解数位dp,请自行学习。(参考https://blog.csdn.net/wust_zzwh/article/details/52100392)
ac代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll t, n;
ll mod;
ll a[20];
ll dp[20][110][110];
ll dfs(int pos, int sum, int res, bool limit){
if(pos==-1) {
if(sum==mod && res==0) return 1;
else return 0;
}
if(!limit && dp[pos][sum][res]!=-1) return dp[pos][sum][res];
ll up=limit?a[pos]:9;
ll ans=0;
for(int i=0;i<=up;i++){
if(i+sum > mod) break;
ans+=dfs(pos-1, sum+i, (res*10+i)%mod, limit && i==a[pos]);
}
if(!limit ) dp[pos][sum][res]=ans;
return ans;
}
ll solve(ll x)
{
ll pos=0;
while(x)//把数位都分解出来
{
a[pos++]=x%10;x/=10;
}
ll ans = 0;
for(int i=1; i<=9*pos; i++){
mod = i;
memset(dp, -1, sizeof(dp));
ans += dfs(pos-1, 0, 0, true);
}
return ans;
}
int main()
{
int Case = 1;
scanf("%d", &t);
while(t--){
scanf("%lld", &n);
printf("Case %d: ", Case++);
printf("%lld\n", solve(n));
}
}