题目1 A Simple Math Problem
8.1
- 问题描述
Lele now is thinking about a simple function f(x).
If x < 10 f(x) = x.
If x >= 10 f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10);
And ai(0<=i<=9) can only be 0 or 1 .
Now, I will give a0 ~ a9 and two positive integers k and m ,and could you help Lele to caculate f(k)%m.
Input
The problem contains mutiple test cases.Please process to the end of file.
In each case, there will be two lines.
In the first line , there are two positive integers k and m. ( k<2*10^9 , m < 10^5 )
In the second line , there are ten integers represent a0 ~ a9.
Output
For each case, output f(k) % m in one line.
Sample Input
10 9999
1 1 1 1 1 1 1 1 1 1
20 500
1 0 1 0 1 0 1 0 1 0
Sample Output
45
104
2.算法
算法1解题思路
套入模板,建立新的数组进行更新
算法1.源代码
#include
#include
#include
using namespace std;
typedef long long ll ;
int mod;
int n=10;
struct node{
int materix[25][25];/
};
//两数组相乘
node mul(node a,node b){
node res;
memset(res.materix ,0,sizeof(res.materix));
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
for(int k=1;k<=n;k++){
res.materix[i][j]=(res.materix[i][j]+a.materix[i][k]*b.materix[k][j]%mod)%mod;
}
return res;
}
//数组快速幂
node ksm(node a,int b)
{
node ans;
memset(ans.materix,0,sizeof(ans.materix));
for(int i=1;i<=n;i++)
ans.materix[i][i]=1;
while(b){
if(b&1) ans=mul(ans,a);
b>>=1;a=mul(a,a);
}
return ans;
}
int main()
{
int k;
while(~scanf("%d%d",&k,&mod))
{
if(k<10)
{
printf("%d\n",k);//当k小于10时原样输出
continue;
}
node a,b;
memset(a.materix,0,sizeof(a.materix));
memset(b.materix,0,sizeof(b.materix));//数组清零
for(int i=1;i<=10;i++)
{
scanf("%d",&a.materix[1][i]);//输入a
}
for(int i=2;i<=10;i++)
a.materix[i][i-1]=1;
for(int i=1;i<=10;i++)
{
b.materix[i][1]=10-i;
}
node ans=ksm(a,k-9);//套入模板
ans=mul(ans,b);
printf("%d\n",ans.materix[1][1]);//输出
}
return 0;
}
- 总结
记住模板