HihoCoder 1151 矩阵快速幂 + 取模

传送门:HihoCoder 1151

题解

  1. 题意 + 递推

    同HDU 1143 传送门: HDU 1143解题报告

  2. 坑点

    因为这题n值比较大, 所以和HDU 1143不同, 必须用快速幂取模, 而使用快速幂加速的时候, 因为递推公式有-1的因子, 所以最终求的ans 可能为负值, 如果为负值, 要加上模数才对

  3. code:

/*
adrui's submission
Language : C++
Result : Accepted
Love : ll
Favorite : Dragon Balls

Standing in the Hall of Fame
*/



#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;

#define debug 0
#define LL long long
#define MOD 12357
#define M(a, b) memset(a, b, sizeof(a))

int n;

struct Matrix {
    LL mat[3][3];                                                       //同样要用LL
    void init() {
        M(mat, 0);
        for (int i = 0; i < 3; i++)
            mat[i][i] = 1;
    }
    void Debug() {
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++) {
                printf("%I64d%c", this->mat[i][j], j == 2 ? '\n' : ' ');    
            }
    }
};

Matrix operator * (Matrix a, Matrix t) {                //矩阵乘法
    Matrix c;
    M(c.mat, 0);

    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
        {
            for (int k = 0; k < 3; k++)
                c.mat[i][j] = (c.mat[i][j] + a.mat[i][k] * t.mat[k][j]) % MOD;
        }

    return c;
}
Matrix operator ^ (Matrix tmp, int b) {                    //快速幂
    Matrix res;
    res.init();

    while (b) {
        if (b & 1) res = res * tmp;
        tmp = tmp * tmp;
        b >>= 1;
        //res.Debug();
    }

    return res;
}
int main() {
#if debug
    freopen("in.txt", "r", stdin);
#endif //debug

    LL f[] = { 1, 3, 11 };

    while (~scanf("%d", &n)) {
        Matrix tmp;
        M(tmp.mat, 0);                                        //构造底数矩阵
        tmp.mat[0][0] = 4;
        tmp.mat[0][1] = -1;
        tmp.mat[1][0] = 1;
        tmp.mat[2][1] = 1;

        if (n & 1)
            puts("0");
        else {
            if (n <= 4) {
                printf("%I64d\n", f[n / 2]);
            }
            else {
                Matrix res = tmp ^ ((n - 4) >> 1);                                //快速幂
                int ans = (11 * res.mat[0][0] + 3 * res.mat[0][1] + res.mat[0][2]) % MOD;
                if (ans < 0)
                    ans += MOD;                                                   //坑点
                printf("%d\n", ans);
            }
        }//ans
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值