首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【51Nod】1126 - 求递推数列的第N项(矩阵快速幂 & C++运算符重载)

【51Nod】1126 - 求递推数列的第N项(矩阵快速幂 & C++运算符重载)

作者头像
FishWang
发布2025-08-26 14:27:53
发布2025-08-26 14:27:53
17200
代码可运行
举报
运行总次数:0
代码可运行

题目链接:点击打开题目


这里写图片描述
这里写图片描述

这里写图片描述
这里写图片描述

代码如下:

代码语言:javascript
代码运行次数:0
运行
复制
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define CLR(a,b) memset(a,b,sizeof(a))
#define PI acos(-1.0)
#define LL long long
const int MOD = 7;
struct Matrix
{
    int h,w;
    int m[3][3];
    void init(int op)
    {
        if (op == 0)        //初始化矩阵 
            CLR(this->m,0);
        else if (op == 1)       //初始化为单位矩阵 
        {
            this->h = this->w = 2;
            CLR(this->m,0);
            this->m[1][1] = this->m[2][2] = 1;
        }
        else if (op == 2)       //初始化为初始矩阵 
        {
            this->h = 1;
            this->w = 2;
            CLR(this->m,0);
            this->m[1][1] = this->m[1][2] = 1;
        }
    }
    void init(int A,int B)
    {
        this->w = this->h = 2;
        CLR(this->m,0);
        this->m[1][1] = A;
        this->m[2][1] = B;
        this->m[1][2] = 1;
    }
    Matrix operator * (Matrix a)
    {
        Matrix t;
        t.h = this->h;
        t.w = a.w;
        t.init(0);
        for (int i = 1 ; i <= this->h ; i++)
        {
            for (int j = 1 ; j <= a.w ; j++)
            {
                if (this->m[i][j])
                    for (int k = 1 ; k <= this->w ; k++)
                    {
                        t.m[i][k] = (t.m[i][k] + this->m[i][j] * a.m[j][k] % MOD) % MOD;
                    }
            }
        }
        return t;
    }
    Matrix quickMod(int n)
    {
        Matrix t;
        t.init(1);
        while (n)
        {
            if (n & 1)
                t = t * (*this);
            *this = (*this) * (*this);
            n >>= 1;
        }
        return t;
    }
};

int main()
{
    int A,B,n;
    scanf ("%d %d %d",&A,&B,&n);
    if (n == 1 || n == 2)
        puts("1");
    else
    {
        Matrix pr,ans,ori;
        pr.init(2);
        ori.init(A,B);
        ori = ori.quickMod(n-2);
        ans = pr * ori;
        printf ("%d\n",(ans.m[1][1] % MOD + MOD) % MOD);
    }
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档