|
A Simple Math ProblemTime Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) |
【题目大意】:
一个方程f(x),式子如下定义:
如果 x < 10,那么 f(x) = x.
如果 x >= 10 ,那么f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10);
并且ai(0<=i<=9) 只可能是 0 或 1 .
现在,给定a0~a9,和整数k,m,现在想让你求 f(k)%m.
【分析】:
小于10时直接输出。大于10时分析式子f(x)=a0*f(x-1)+a1*f(x-2)+a2*f(x-3)+……+a9*f(x-10),转化的构造矩阵为
|0
|0
|................1|
|a9
如样例一转化为:
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1
发现只需将构造矩阵自乘K-9次即可出现需要的那一个,这里可以用快速幂的思想来做这一步操作,即矩阵自乘快速幂优化
【代码】:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define MAX 11
struct mat{int c[MAX][MAX];};
mat a;
int K,P,ans=0;
mat mult(mat A,mat B)
{
mat now;
for(int i=1;i<=10;i++)
for(int j=1;j<=10;j++)
{
now.c[i][j]=0;
for(int k=1;k<=10;k++)
now.c[i][j]=(now.c[i][j]+A.c[i][k]*B.c[k][j])%P;
}
return now;
}
mat power(mat now,int n)
{
if(n==1) return now;
else if(n&1)
return mult(power(now,n-1),now);
else
{
mat use;
use=power(now,n/2);
return mult(use,use);
}
}
void work()
{
mat now;
ans=0;
now=power(a,K-9);
for(int i=1;i<=10;i++)
ans=(ans+now.c[10][i]*(i-1))%P;//这里的i-1即f(0-9)
}
int main()
{
//freopen("input.in","r",stdin);
//freopen("output.out","w",stdout);
while(scanf("%d%d",&K,&P)!=EOF)
{
for(int i=10;i>=1;i--)
scanf("%d",&a.c[10][i]);
if(K<10) {printf("%d\n",K%P);continue;}
for(int i=1;i<10;i++)//建立构造矩阵
{
for(int j=1;j<=10;j++)
{
if(j==i+1) a.c[i][j]=1;
else a.c[i][j]=0;
}
}
work();
printf("%d\n",ans);
}
//system("pause");
return 0;
}
转载注明出处:http://blog.csdn.net/u011400953