矩阵快速幂要推出递推式,左矩阵右矩阵,带入模板
分享一篇博客:https://blog.csdn.net/u012061345/article/details/52224623
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdlib.h>
#include <string.h>
using namespace std;
#define ll long long
#define debug(x, y) cout <<x<<" "<<y<<"\n"
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
#define endl "\n"
#define pii pair<int, int>
#define inf 100000000
#define gg cout<<"_________"<<endl
const int maxn = 222222;
const int N = 20;
const ll mod = 2147493647;
struct matrix
{
int row, col;
ll mat[N][N];
matrix(int _row=0, int _col=0)
{
init(_row, _col);
}
void init(int _row, int _col)
{
row = _row, col = _col;
memset(mat, 0, sizeof mat);
}
matrix operator* (matrix b)
{
matrix c(row, b.col);
for(int i = 1; i <= row; i++)
for(int j = 1; j <= b.col; j++)
for(int k = 1; k <= col; k++)
c.mat[i][j] = (c.mat[i][j] + mat[i][k] * b.mat[k][j] % mod) % mod;
return c;
}
};
matrix mod_pow(matrix a, ll b, ll p)
{
matrix ans(7, 7);
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;
}
matrix standard(7, 7);
ll mp[8][8] = {
0,0,0,0,0,0,0,0,
0,1,2,1,4,6,4,1,
0,1,0,0,0,0,0,0,
0,0,0,1,4,6,4,1,
0,0,0,0,1,3,3,1,
0,0,0,0,0,1,2,1,
0,0,0,0,0,0,1,1,
0,0,0,0,0,0,0,1
};
void init()
{
for(int i = 1; i <= 7; ++i)
for(int j = 1; j <= 7; ++j)
standard.mat[i][j] = mp[i][j];
}
int main()
{
int t;
init();
scanf("%d", &t);
while(t--)
{
ll n, a, b;
scanf("%lld%lld%lld", &n, &a, &b);
if(n == 1) printf("%lld\n", a);
else if(n == 2) printf("%lld\n", b);
else {
matrix f(7, 7);
f.mat[1][1] = (ll) b; f.mat[2][1] = (ll) a;
f.mat[3][1] = (ll) 16; f.mat[4][1] = (ll) 8;
f.mat[5][1] = (ll) 4; f.mat[6][1] = (ll) 2;
f.mat[7][1] = (ll) 1;
f = mod_pow(standard, n-2, mod)*f;
printf("%lld\n", f.mat[1][1]);
}
}
return 0;
}