CodeForces 507D The Maths Lecture(数位dp)

本文介绍了一种使用数位动态规划(数位DP)的方法来解决一个有趣的数学问题:给定三个整数n, k, m,求解有多少个正整数x,其十进制表示恰好有n位,并且存在某个正整数y作为x的后缀,使得y除以k的余数为0,最终结果需要对m取模。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Amr doesn’t like Maths as he finds it really boring, so he usually sleeps in Maths lectures. But one day the teacher suspected that Amr is sleeping and asked him a question to make sure he wasn’t.

First he gave Amr two positive integers n and k. Then he asked Amr, how many integer numbers x > 0 exist such that:

Decimal representation of x (without leading zeroes) consists of exactly n digits;
There exists some integer y > 0 such that:
;
decimal representation of y is a suffix of decimal representation of x.
As the answer to this question may be pretty huge the teacher asked Amr to output only its remainder modulo a number m.

Can you help Amr escape this embarrassing situation?

Input
Input consists of three integers n, k, m (1 ≤ n ≤ 1000, 1 ≤ k ≤ 100, 1 ≤ m ≤ 109).

Output
Print the required number modulo m.
题意不是很难理解,就不解释了。感觉还是很容易想到应该用数位dp的。。。。
dp数组我开了4维,dp[i][j][m][ln]代表前面还有i项需要处理,j为1代表已经处理过的n-i全为0,j为1代表不全为0,之所以要开j是因为题目中的后缀必须是大于0的数字,m代表已经处理过的n-i位的后缀取模题目中的k,n代表已经处理的n-i位中是否已经有modk==0的后缀,然后记忆化搜一波就ok。
还需要注意的一点就是这题和一般的数位dp不太一样,一般的数位dp都是从前往后搜,但这题需要从后往前搜,因为这个题是后缀,从后往前搜的一个最大的缺点就是无法控制每一位应该搜到几,比如我要求搜的数字不能大于123,如果从前往后搜很容易就可以用limit控制每一位应该搜到9还是那一位对应的数字,但如果从后向前搜,拿最后一位举例子,我根本不知道最后一位我需要搜索到9还是搜索到3。。。所以这个题也没有控制最大的数字是多少,只是说了n位。
直接上代码。。。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
using namespace std;
#define maxn 1010
#define ll long long
#define angel 0x3f3f3f3f
ll dp[maxn][2][105][2];
int sum[maxn];//每一位的权值
ll n,m,mod;
ll dfs(int length,int pre,int div,int success)
{
    if(length==0)
        return success;
    if(dp[length][pre][div][success]!=-1)
        return dp[length][pre][div][success];
    int start;
    if(length==1)
        start=1;//不能有前导0
    else
        start=0;
    ll ans=0;
    for(int i=start; i<=9; i++)
    {
        int key=((i==0)&&pre);//后面是否全为0
        int And=(sum[n-length]*i%m+div)%m;//加上当前位modm是几
        ans+=dfs(length-1,key,And,((And==0)&&(key==0))||success);//success只有当And等于0并且后面的数不全为0时才是1
        ans%=mod;
    }
    dp[length][pre][div][success]=ans;
    return ans;
}
int main()
{
    scanf("%lld%lld%lld",&n,&m,&mod);
    sum[1]=10;
    for(int i=2; i<=n; i++)
    {
        sum[i]=sum[i-1]*10;
        sum[i]%=m;
    }
    memset(dp,-1,sizeof(dp));
    ll ans=0;
    int start;
    if(n==1)
        start=1;
    else
        start=0;
    for(int i=start; i<=9; i++)
    {
        ans+=dfs(n-1,i==0,i%m,(i%m==0)&&(i!=0));
        ans%=mod;
    }
    printf("%lld\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值