Q老師 對數列有一種非同一般的熱愛,尤其是優美的斐波那契數列。
這一天,Q老師 爲了增強大家對於斐波那契數列的理解,決定在斐波那契的基礎上創建一個新的數列 f(x) 來考一考大家。數列 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 或 1。
Q老師 將給定 a0~a9,以及兩個正整數 k m,詢問 f(k) % m 的數值大小。
聰明的你能通過 Q老師 的考驗嗎?
輸入:
輸出文件包含多組測試用例,每組測試用例格式如下:
第一行給定兩個正整數 k m。(k < 2e9, m < 1e5)
第二行給定十個整數,分別表示 a0~a9。
輸出:
對於每一組測試用例輸出一行,表示 f(k) % m 的數值大小。
樣例輸入:
10 9999
1 1 1 1 1 1 1 1 1 1
20 500
1 0 1 0 1 0 1 0 1 0
樣例輸出:
45
104
由於數據k < 2e9, m < 1e5,所以需要用矩陣快速冪來解決。
由公式f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10)可以構造出矩陣。
f(n) a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 f(n-1)
f(n-1) 1 0 0 0 0 0 0 0 0 0 f(n-2)
f(n-2) 0 1 0 0 0 0 0 0 0 0 f(n-3)
f(n-3) 0 0 1 0 0 0 0 0 0 0 f(n-4)
f(n-4) 0 0 0 1 0 0 0 0 0 0 f(n-5)
ans[n]= f(n-5) = 0 0 0 0 1 0 0 0 0 0 × f(n-6)
f(n-6) 0 0 0 0 0 1 0 0 0 0 f(n-7)
f(n-7) 0 0 0 0 0 0 1 0 0 0 f(n-8)
f(n-8) 0 0 0 0 0 0 0 1 0 0 f(n-9)
f(n-9) 0 0 0 0 0 0 0 0 1 1 f(n-10)
ans[n]=t^(n-9)*ans[9],t是上面10×10的矩陣。
#include<iostream>
#include<string.h>
#define ll long long
using namespace std;
const int N=10;
ll k,m;
struct Matrix{
ll x[N][N];
Matrix operator*(const Matrix& t)const
{
Matrix ret;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
ret.x[i][j]=0;
for(int k=0;k<N;k++)
{
ret.x[i][j]+=x[i][k]*t.x[k][j]%m;
ret.x[i][j]%=m;
}
}
}
return ret;
}
Matrix()
{
memset(x,0,sizeof(x));
}
Matrix(const Matrix& t)
{
memcpy(x,t.x,sizeof(x));
}
};
Matrix quick_pow(Matrix a,int x)
{
Matrix ret;
memset(ret.x,0,sizeof(ret.x));
for(int i=0;i<N;i++)
{
ret.x[i][i]=1;
}
while(x)
{
if(x&1)
{
ret=ret*a;
}
a=a*a;
x>>=1;
}
return ret;
}
int main()
{
while(cin>>k>>m)
{
Matrix ma;
for(int i=0;i<10;i++)
{
cin>>ma.x[0][i];
}
for(int i=1;i<10;i++)
{
ma.x[i][i-1]=1;
}
Matrix tmp=quick_pow(ma,k-9);
ll ans=0;
for(int i=0;i<10;i++)
{
ans+=tmp.x[0][i]*(9-i);
ans=ans%m;
}
cout<<ans<<'\n';
}
}