题意:给出f(n)的递推式,共的项,求f(n)mod m的值
解析:
- f[n]=a1*f[n-1]+a2*f[n-2]+...+ad*f[n-d];
- 由于n太大,不能直接递推,需要用矩阵快速幂来解决,时间复杂度为O(d^3logn)
- 举例,d=5的矩阵关系式为:
- |a1 a2 a3 a4 a5| | f[n] | | f[n+1] |
- |1 | | f[n-1] | | f[n] |
- | 1 | * | f[n-2] | = | f[n-1] | (空白处为0)
- | 1 | | f[n-3] | | f[n-2] |
- | 1 | | f[n-4] | | f[n-3] |
#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
typedef long long LL;
LL d,m,f[26];
struct node
{
LL a[16][16];
};
node multi(node x,node y)
{
node t;
memset(t.a,0,sizeof(t.a));
int i,j,k;
for(i=1; i<=d; i++)
{
for(j=1; j<=d; j++)
{
for(k=1; k<=d; k++)
t.a[i][j]=(t.a[i][j]+x.a[i][k]*y.a[k][j])%m;
}
}
return t;
}
LL find(LL n,node sa)
{
node t;
memset(t.a,0,sizeof(t.a));
for(int i=1; i<=d; i++) t.a[i][i]=1;
while(n)
{
if(n&1) t=multi(t,sa);
sa=multi(sa,sa);
n>>=1;
}
LL ans=0;
for(int i=1;i<=d;i++)
ans=(ans+t.a[1][i]*f[i])%m;
return ans;
}
int main()
{
int i;
LL n;
node sa;
while(scanf("%lld%lld%lld",&d,&n,&m)&&d)
{
memset(sa.a,0,sizeof(sa.a));
for(i=1; i<=d; i++)
scanf("%d",&sa.a[1][i]);
for(i=d; i>=1; i--)
scanf("%d",&f[i]);
for(i=2; i<=d; i++)
sa.a[i][i-1]=1;
if(n<=d) printf("%lld\n",f[d-n+1]%m);
else
printf("%lld\n",find(n-d,sa));
}
return 0;
}