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
input | output |
---|---|
|
|
动态转移方程为
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 |
---|---|
1 | 0 |
#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;
}