Recursive sequence HDU - 5950
Posted Jozky86
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Recursive sequence HDU - 5950相关的知识,希望对你有一定的参考价值。
题意:
给你一个式子:f[n]=2f[n-2]+f[n-1]+n4
给你f[1]和f[2],给你一个n,求f[n]
f[1],f[2],n<=231
题解:
很明显,矩阵快速幂,但是太久没做这种题,我都忘了怎么推导矩阵的了
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
typedef long long ll;
int t, n, a, b;
ll mod = 2147493647;
struct Matrix
{
ll mat[15][15];
Matrix()
{
memset(mat, 0, sizeof(mat));
}
friend Matrix operator * (Matrix A, Matrix B)
{
Matrix ans;
for(int i = 1; i <= 7; ++ i)
{
for(int j = 1; j <= 7; ++ j)
{
for(int k = 1; k <= 7; ++ k)
{
ans.mat[i][j] += (A.mat[i][k] * B.mat[k][j]) % mod;
ans.mat[i][j] %= mod;
}
}
}
return ans;
}
};
Matrix quick_matrix(Matrix A, int b)
{
Matrix ans;
for(int i = 1; i <= 7; ++ i)
{
ans.mat[i][i] = 1;
}
while(b)
{
if(b & 1)
{
ans = ans * A;
}
A = A * A;
b >>= 1;
}
return ans;
}
int main()
{
cin >> t;
while(t--)
{
cin >> n >> a >> b;
if(n == 1 || n == 2)
{
if(n == 1)
cout << a << endl;
else
cout << b << endl;
continue;
}
Matrix A, B;
A.mat[1][1] = b;
A.mat[2][1] = a;
A.mat[3][1] = 3 * 3 * 3 * 3;
A.mat[4][1] = 3 * 3 * 3;
A.mat[5][1] = 3 * 3;
A.mat[6][1] = 3;
A.mat[7][1] = 1;
B.mat[1][1] = 1;
B.mat[1][2] = 2;
B.mat[1][3] = 1;
B.mat[2][1] = 1;
B.mat[3][3] = 1;
B.mat[3][4] = 4;
B.mat[3][5] = 6;
B.mat[3][6] = 4;
B.mat[3][7] = 1;
B.mat[4][4] = 1;
B.mat[4][5] = 3;
B.mat[4][6] = 3;
B.mat[4][7] = 1;
B.mat[5][5] = 1;
B.mat[5][6] = 2;
B.mat[5][7] = 1;
B.mat[6][6] = 1;
B.mat[6][7] = 1;
B.mat[7][7] = 1;
B = quick_matrix(B, n - 2);
A = B * A;
cout << A.mat[1][1] << endl;
}
return 0;
}
以上是关于Recursive sequence HDU - 5950的主要内容,如果未能解决你的问题,请参考以下文章
HDu 5950 Recursive sequence(矩阵快速幂)
HDU5950-Recursive sequence(矩阵快速幂)