藍橋杯演算法提高——遞推求值(矩陣快速冪)
阿新 • • 發佈:2019-02-09
問題描述
已知遞推公式:
F(n, 1)=F(n-1, 2) + 2F(n-3, 1) + 5,
F(n, 2)=F(n-1, 1) + 3F(n-3, 1) + 2F(n-3, 2) + 3.
初始值為:F(1, 1)=2, F(1, 2)=3, F(2, 1)=1, F(2, 2)=4, F(3, 1)=6, F(3, 2)=5。
輸入n,輸出F(n, 1)和F(n, 2),由於答案可能很大,你只需要輸出答案除以99999999的餘數。
輸入格式
輸入第一行包含一個整數n。
輸出格式
輸出兩行,第一行為F(n, 1)除以99999999的餘數,第二行為F(n, 2)除以99999999的餘數。
樣例輸入
4
樣例輸出
14
21
資料規模和約定
1<=n<=10^18。
看到遞推就知道要用矩陣快速冪了,
參照:
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <cstdio>
#include <set>
#include <math.h>
#include <algorithm>
#include <queue>
#include <iomanip>
#define INF 0x3f3f3f3f
#define MAXN 10000005
#define Mod 99999999
using namespace std;
const int N = 8;
long long n;
struct Matrix
{
long long mat[N][N];
};
Matrix unit_mat=
{
1,0,0,0,0,0,0,0,
0,1,0,0,0,0,0,0,
0,0,1,0,0,0,0,0,
0,0,0,1,0,0,0,0,
0,0,0,0,1,0,0,0,
0,0,0,0,0,1,0,0,
0,0,0,0,0,0,1,0,
0 ,0,0,0,0,0,0,1,
};
Matrix mul(Matrix a,Matrix b)
{
Matrix res;
for(int i=0; i<N; ++i)
for(int j=0; j<N; ++j)
{
res.mat[i][j]=0;
for(int k=0; k<N; ++k)
{
res.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
res.mat[i][j]%=Mod;
}
}
return res;
}
Matrix pow_matrix(Matrix a,long long n)
{
Matrix res = unit_mat;
while(n!=0)
{
if(n%2)
res=mul(res,a);
a=mul(a,a);
n>>=1;
}
return res;
}
int main()
{
Matrix tmp,arr;
while(~scanf("%I64d",&n))
{
if(n==1)
{
printf("%d\n",2%Mod);
printf("%d\n",3%Mod);
}
else if(n==2)
{
printf("%d\n",1%Mod);
printf("%d\n",4%Mod);
}
else if(n==3)
{
printf("%d\n",6%Mod);
printf("%d\n",5%Mod);
}
else
{
memset(arr.mat,0,sizeof(arr.mat));
memset(tmp.mat,0,sizeof(tmp.mat));
arr.mat[0][0]=6;
arr.mat[1][0]=5;
arr.mat[2][0]=1;
arr.mat[3][0]=4;
arr.mat[4][0]=2;
arr.mat[5][0]=3;
arr.mat[6][0]=arr.mat[7][0]=1;
tmp.mat[0][1]=tmp.mat[1][0]=tmp.mat[2][0]=tmp.mat[3][1]=tmp.mat[4][2]=tmp.mat[5][3]=tmp.mat[6][6]=tmp.mat[7][7]=1;
tmp.mat[0][4]=tmp.mat[1][5]=2;
tmp.mat[1][4]=tmp.mat[1][7]=3;
tmp.mat[0][6]=5;
Matrix p=pow_matrix(tmp,n-3);
p=mul(p,arr);
long long ans1=p.mat[0][0]%Mod;
long long ans2=p.mat[1][0]%Mod;
printf("%I64d\n",ans1);
printf("%I64d\n",ans2);
}
}
return 0;
}