2018 ACM 国际大学生程序设计竞赛上海大都会赛重现赛 J-Beautiful Numbers

4 篇文章 0 订阅
1 篇文章 0 订阅

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

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值