Ural 1009 K-based Numbers. Version 3 (DP+矩阵快速幂+快速乘)

本文探讨了在给定长度N、基数K和模数M的情况下,如何计算不含连续零的有效K进制数的数量。通过动态规划和矩阵快速幂的方法,解决了一个数学问题,涉及到大数运算和算法优化。

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

Let’s consider K-based numbers, containing exactly N digits. We define a number to be valid if its K-based notation doesn’t contain two successive zeros. For example:

  • 1010230 is a valid 7-digit number;
  • 1000198 is not a valid number;
  • 0001235 is not a 7-digit number, it is a 4-digit number.

Given three numbers N, K and M, you are to calculate an amount of valid K based numbers, containing N digits modulo M.

You may assume that 2 ≤ N, K, M ≤ 10 18.

Input

The numbers N, K and M in decimal notation separated by the line break.

Output

The result in decimal notation.

Example

inputoutput
2
10
100
90

 

动态转移方程为

dp[i]=(dp[i-1]+dp[i-2])*(i-1);  (dp[i]的含义为 i位k进制有效数字的数量)

初始矩阵为

dp[1]=k-1
dp[0]=1

 构造矩阵为

 k-1

k-1
10
#include <iostream>

using namespace std;

struct node{
    long long a[2][2];
}t,kk,ans;

long long n,k,mod;

long long quick_mul(long long a,long long b)//快速乘
{
    long long ans=0;
    long long kk=a;
    while(b)
    {
        if(b&1)
        {
            ans=(ans+kk)%mod;
        }
        kk=(kk*2)%mod;
        b>>=1;
    }
    return ans;
}

node Matrix_mul(node x,node y)//矩阵乘法
{
    node now;
    now.a[0][0]=(quick_mul(x.a[0][0],y.a[0][0])+quick_mul(x.a[0][1],y.a[1][0]))%mod;
    now.a[0][1]=(quick_mul(x.a[0][0],y.a[0][1])+quick_mul(x.a[0][1],y.a[1][1]))%mod;
    now.a[1][0]=(quick_mul(x.a[1][0],y.a[0][0])+quick_mul(x.a[1][1],y.a[1][0]))%mod;
    now.a[1][1]=(quick_mul(x.a[1][0],y.a[0][1])+quick_mul(x.a[1][1],y.a[1][1]))%mod;
    return now;
}

node quick_Matrix()//矩阵快速幂
{
    n--;
    ans.a[0][0]=ans.a[1][1]=1;
    ans.a[0][1]=ans.a[1][0]=0;
    kk=t;
    while(n)
    {
        if(n&1)
        {
            ans=Matrix_mul(ans,kk);
        }
        kk=Matrix_mul(kk,kk);
        n>>=1;
    }
    return ans;
}

int main()
{
    while(cin >> n >> k >> mod)
    {
        t.a[0][0]=k-1;//构造矩阵
        t.a[0][1]=k-1;
        t.a[1][0]=1;
        t.a[1][1]=0;
        quick_Matrix();
        cout << (quick_mul(ans.a[0][0],k-1)+ans.a[0][1])%mod << endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值