您的位置:首页 > 其它

蓝桥杯算法提高——递推求值(矩阵快速幂)

2017-03-30 19:18 381 查看
问题描述

  已知递推公式:

  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。

看到递推就知道要用矩阵快速幂了,

参照:

http://blog.csdn.net/liangzhaoyang1/article/details/61415350

#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

;
};
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: