A Simple Math Problem
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4503 Accepted Submission(s): 2714
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.
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.
A: Fn Fn-1......Fn-10
B: Fn-1 Fn-2......Fn-11
要由下面的矩陣的到上面的就要乘以一個十一階的已知矩陣,根據矩陣乘法可以求出就這個矩陣爲:
暫時記爲c;若求n=11,則輸出最上面矩陣的A[1][1];
用B*c^1就好。這樣我們就需要知道B矩陣的值即:F10 F9 F8 ......F1 F0,可以根據題意求出
代碼:
#include <cstdio>
#include <stack>
#include <queue>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define LL long long
int MOD;
struct Matrix
{
int h,w;
int m[15][15];
};
Matrix Matrix_multiply(Matrix a,Matrix b)
{
Matrix c;
c.h=a.h;
c.w=b.w;
CLR(c.m,0);
for(int i=1;i<=a.h;i++)
{
for(int j=1;j<=a.w;j++)
{
if(a.m[i][j]==0)
continue;
for(int k=1;k<=b.w;k++)
c.m[i][k]=(c.m[i][k]+a.m[i][j]*b.m[j][k]%MOD)%MOD;
}
}
return c;
}
Matrix Quick(Matrix a,int n)
{
Matrix ans;
ans.h=ans.w=a.h;
CLR(ans.m,0);
for(int i=1;i<=a.h;i++)
ans.m[i][i]=1;
while(n)
{
if(n&1)
ans=Matrix_multiply(ans,a);
n>>=1;
a=Matrix_multiply(a,a);
}
return ans;
}
int main()
{
int k;
int a[11];
while(~scanf("%d%d",&k,&MOD))
{
if(k<10)
printf("%d\n",k%MOD);
else
{
Matrix pr,now;
pr.h=pr.w=11;
CLR(pr.m,0);
for(int i=1;i<=10;i++)
{
scanf("%d",&a[i]);
pr.m[i][1]=a[i];
}
for(int i=2;i<=11;i++)
pr.m[i-1][i]=1;
now.h=1,now.w=11;
CLR(now.m,0);
now.m[1][1]=(9*a[1]+8*a[2]+7*a[3]+6*a[4]+5*a[5]+4*a[6]+3*a[7]+2*a[8]+a[9]);
for(int i=2;i<=10;i++)
now.m[1][i]=11-i;
Matrix ans;
ans=Matrix_multiply(now,Quick(pr,k-10));
printf("%d\n",ans.m[1][1]);
}
}
return 0;
}