题意:f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
给你 A ,B,n 求出f(n)
思路:一看就是常系数线性齐次递推关系,矩阵二分幂
矩阵二分幂:http://blog.youkuaiyun.com/leonharetd/article/details/8956190
| f[n] | = | a*f[n-1] + b*f[n-2] |
| f[n-1] | | f[n-1] |
根据矩阵乘法得到 原式 = | a b | * | f[n-1] |
| 1 0 | | f[n-2] |
同理:
| f[n-1] | = | a b | * | f[n-21 |
| f[n-2] | | 1 0 | | f[n-2] |
| f[n] | = | a b | ^ n-1 * | f[1] |
| f[n-1] | | 1 0 | | f[0] |
问题就转化为了求
| a b | 的n - 1次方可以用矩阵二分幂
| 1 0 |
代码:#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct Matrix
{
int row[2][2];
};
Matrix num,ans,r;
int a,b,n;
void init()
{
num.row[0][0] = 0,num.row[0][1] = b;
num.row[1][0] = 1,num.row[1][1] = a;
r.row[0][0] = 1,r.row[0][1] = 1;
r.row[1][0] = 1,r.row[1][1] = (a+b) % 7;
}
Matrix Matrix_Mul(Matrix a,Matrix b)
{
Matrix sum;
int i,j;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
sum.row[i][j] = ( (a.row[i][0]*b.row[0][j])%7 + (a.row[i][1]*b.row[1][j] )% 7 ) % 7;
}
}
return sum;
}
void getdata(int m)
{
ans = num;
while(m)
{
if(m&1)
r = Matrix_Mul(r,ans);
ans = Matrix_Mul(ans,ans);
m = m >> 1;
}
}
int main()
{
while(scanf("%d%d%d",&a,&b,&n) != EOF)
{
if(a == 0 && b == 0 && n == 0 )
break;
init();
getdata(--n);
printf("%d\n",r.row[0][0]);
}
return 0;
}

本文介绍了一种利用矩阵快速幂解决特定类型的常系数线性齐次递推数列的方法。通过矩阵运算,可以高效地计算出递推数列的第n项值,并提供了一个具体的C++实现示例。
340

被折叠的 条评论
为什么被折叠?



