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
#include
#include
#include
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;
}

你可能感兴趣的:(Hihocoder,数论-矩阵快速幂&&快速幂)