上海大都会重现赛 Beautiful Numbers(数位DP)+ 数位DP小结

链接:https://www.nowcoder.com/acm/contest/163/J
来源:牛客网
 

时间限制:C/C++ 8秒,其他语言16秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述

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且能被自己所有位上数之和整除的数的个数。

题解:数位DP,枚举和的所有可能,枚举每一个位置的所有可能,记忆化没有限制时的len,sum,remain的状态,且在没有限制的时候直接使用大幅度降低复杂度.....

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e7+7;

ll dp[20][105][150];
int a[20],mod;
ll dfs(int len,int sum,int remain,bool limit) //目前枚举的位数,各位和,取余mod的余数,限制
{
    if(len==0) return sum==mod && remain==0; //当各位和与自己期望的相同且枚举的数字是各位和的倍数就返回1
    if(!limit && dp[len][sum][remain]!=-1) return dp[len][sum][remain];//记忆化记录的是没有限制的普遍情况,如果有限制,记忆化的一定是错的
    int up=limit?a[len]:9;//有限制则上限是a[len],没有限制是9
    ll cur=0;
    for(int i=0;i<=up;i++)
    {
        if(i+sum>mod) break; //剪枝,和已经大于期望的mod,则直接结束
        cur+=dfs(len-1,sum+i,(remain*10+i)%mod,limit && i==a[len]);//当这位有限制且已枚举到上限则下一位有限制
    }
    return limit?cur:dp[len][sum][remain]=cur;
}

ll solve(ll x)
{
    memset(a,0,sizeof(a));
    int k=0;
    while(x)
    {
        a[++k]=x%10;
        x/=10;
    }
    ll ans=0;
    for(int i=1;i<=9*k;i++) //枚举期望的和
    {
        memset(dp,-1,sizeof(dp));//每次枚举的只是这次的期望和
        mod=i;
        ans+=dfs(k,0,0,true);
    }
    return ans;
}

int main()
{
    int T;
    scanf("%d",&T);
    for(int cas=1;cas<=T;cas++)
    {
        ll n;
        scanf("%lld",&n);

        printf("Case %d: ",cas);
        cout<<solve(n)<<endl;
    }
    return 0;
}

 

对于数位DP,其实是一种记忆化搜索,当搜索完一颗子树的k个孩子,返回到父节点的时候对于父节点进行记忆化,以后再经过就可以直接得到结果,因为对于每个节点都是记录了他10个孩子的情况,但是当有限制的时候,他的孩子的数量可能无法达到十个,那么你记忆化的就将是一个错误答案,同理当有限制的时候同样不能直接使用此时的记忆。

数位DP是一种从高位向低位枚举同时对每一位进行DP的操作,DP数组的保存,因为是记忆化节点的情况,所以第一维要记录节点的层数,然后再根据题意确认他的第二维第三维......,比如这道题中dp数组开三维,第二维是记录数位和,第三维记录的是最终取余期望的数位和后的答案。对于状态的选择,关键在于区分节点是否相同,考虑是否可以使用记忆化。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值