模板题(hnust-1713)
题目描述
Ada is 5 years old, and she is learning additions. Her father writes some exercises for her.
1+11=?
2+22=?
3+33=?
“It is easy”, she writes the answer correctly. “Try to answer the following questions”,
1+11+111=?
2+22+222+2222=?
Ada scratches her head. “It’s too difficult”.
So, help Ada to compute the value of equation a+aa+aaa+… which have n items. Since the answer may be quite large, you have to module it by an integer m.
输入
Input contains at most 1000 test cases. Each test case contains only one line.
Each line will contain three integers a, n and m. (1<=a<=9, 1<=n<231-1, 1<=m<=100007). Process to end of file.
输出
For each test case, output the value of (a+aa+aaa+… .)%m。
思路:
题目有明显的递推关系,很容易想到矩阵快速幂,所以找出递推式套用矩阵快速幂模板,很快就能解出来,下面说一下怎么求递推式
首先假设a=1
那么 a1=1, a2=11, a3=111, a4=1111, a5=11111, a6=111111
s1=1, s2=12, s3=123, s4=1234, s5=12345, s6=123456
再看a=2时
a1=2, a2=22, a3=222, a4=2222, a5=22222, a6=222222
s1=2, s2=24, s3=246, s4=2468, s5=24690, s6=246912
很快就可以得到递推式Sn=10*Sn-1+a*10(当然递推式不只一种)
然后就是根据递推式构建矩阵(这个矩阵很容易构建就不细讲了)
构建矩阵A: 构建矩阵B:
Sn 1 n 10 0 0
0 0 0 0 1 1
0 0 0 a 0 1
通过A*B可以推出我们想要的任意一项(下面A[0][0]表示矩阵A的(1,1)个元素)
S1=A[0][0]
s2=(A*B)[0][0]
s3=(A*B*B)[0][0]
…
Sn=(A*B^(n-1))[0][0]
此过程可以通过矩阵快速幂加速。
代码:
#include <iostream>
#include<cstring>
using namespace std;
typedef long long ll;
struct mat
{
ll m[5][5];
};
mat mul(mat a,mat b,int m)
{
mat t;
memset(t.m,0,sizeof t);
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
for(int k=0;k<3;k++)
{
t.m[i][j]+=a.m[i][k]*b.m[k][j]%m;
}
}
}
return t;
}
mat quick_pow(mat a,int b,int m)
{
mat t;
memset(t.m,0,sizeof t);
for(int i=0;i<3;i++) t.m[i][i]=1;
while(b)
{
if(b&1) t=mul(t,a,m);
a=mul(a,a,m);
b=b>>1;
}
return t;
}
int main()
{
int a,n,m;
while(cin>>a>>n>>m)
{
mat ans;
ans.m[0][0]=10, ans.m[0][1]=0, ans.m[0][2]=a;
ans.m[1][0]=0, ans.m[1][1]=1, ans.m[1][2]=0;
ans.m[2][0]=0, ans.m[2][1]=1, ans.m[2][2]=1;
ans=quick_pow(ans,n-1,m);
cout<<(ans.m[0][0]*a+ans.m[0][1]+ans.m[0][2]*2)%m<<endl;
}
return 0;
}