洛谷p1939矩阵加速(数列)(矩阵快速幂模板题)

洛谷P1939
题目链接

题目描述

已知一个数列 aa,它满足:
在这里插入图片描述
求 a数列的第 n 项对 109+7 取余的值。

思路:

数据范围很大,直接递推肯定TLE,由递推想到矩阵快速幂,矩阵快速幂运算思想与普通快速幂运算一致,只不过借助了矩阵运算。解题的关键在于得到目标矩阵和构造初始矩阵。一定要注意矩阵的左乘和和右乘!

code:
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#define debug(x) cout << #x << ":" << x << endl;
#define fi first
#define se second
using namespace std;
typedef long long ll;
const double eps = 1e-10;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double pi = acos(-1.0);
const int mod = 1e9 + 7;
const int maxn = 2e5 + 10;

struct mat{
    ll m[3][3];
} ans, tran;

void init()
{
    memset(ans.m, 0, sizeof ans.m);
    memset(tran.m, 0, sizeof tran.m);
    ans.m[0][0] = ans.m[1][0] = ans.m[2][0] = 1;//目标矩阵
    tran.m[0][0] = tran.m[0][2] = tran.m[1][0] = tran.m[2][1] = 1;//初始矩阵
}

mat mul(mat a,mat b)
{//矩阵运算
    mat ret;
    memset(ret.m, 0, sizeof ret.m);
    for (int i = 0; i < 3;i++){
        for (int j = 0; j < 3;j++){
            for (int k = 0; k < 3;k++){
                ret.m[i][j] = (ret.m[i][j] + a.m[i][k] * b.m[k][j]) % mod;
            }
        }
    }
    return ret;
}

void qpow(int a)
{//快速幂运算
    while(a){
        if(a&1)
            ans = mul(tran, ans);//表示矩阵tran.m*ans.m,不要写反了!
        a >>= 1;
        tran = mul(tran, tran);
    }
}

int main()
{
    int n, t;
    scanf("%d", &t);
    while(t--){
        scanf("%d", &n);
        if(n<=3)
           puts("1");
        else {
            init();
            qpow(n-3);
            int a = ans.m[0][0];
            printf("%lld\n", a);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值