UVA 10689 矩阵快速幂 + 快速幂取模

uva 10689

题意

 a, b任意给定求出f(n)的后m位数

题解

  1. 构造矩阵
  2. 去快速幂求模数10 ^ m
  3. 矩阵快速幂求f(n)
  4. 输出答案

经验值~get

能用int表示的数据范围尽量不要用long long, 两发PE

code:

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

Standing in the Hall of Fame
*/


#include
#include
#include
#include
#include
#include
#include
using namespace std;

#define M(a, b) memset(a, b, sizeof(a))
#define mid ((l + r) >> 1)
#define ls rt << 1, l, mid
#define rs rt << 1|1, mid + 1, r
#define lowbit(x) (x & (-x))
#define LL long long
#define REP(n) for(int i = 0; i < n; i++)
#define debug 0
const LL  mod(1e9 + 7);

int a, b, n, m;

struct Matrix {
    int mat[2][2];                                                      
    void init1() {                                                          //单位矩阵
        M(mat, 0);
        for (int i = 0; i < 2; i++)
            mat[i][i] = 1;
    }
    void init2() {                                                          //费马小定理
        mat[0][0] = 0;
        mat[0][1] = mat[1][0] = mat[1][1] = 1;
    }
};

Matrix operator * (Matrix a, Matrix b) {                                    //矩阵乘法
    Matrix c;   
    M(c.mat, 0);
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++)
            {
                for (int k = 0; k < 2; k++)
                    c.mat[i][j] += (a.mat[i][k] * b.mat[k][j]) % m;
                c.mat[i][j] %= m;
            }
        }

    return c;
}

Matrix Matrix_fast_mod(int b) {                                             //快速矩阵幂
    Matrix res, tmp;
    res.init1();                                                            //单位矩阵
    tmp.init2();

    while (b) {
        if (b & 1) res = tmp * res;
        tmp = tmp * tmp;
        b >>= 1;
    }
    return res;
}

int  fast_mul(int a, int b) {
    int res = 1;
    while (b) {
        if (b & 1) res = res * a;
        a = a * a;
        b >>= 1;
    }

    return res;
}

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

    int t;
    scanf("%d", &t);

    while (t--) {
        scanf("%d%d%d%d", &a, &b, &n, &m);

        m = fast_mul(10, m);                                        //模数
        Matrix tmp = Matrix_fast_mod(n - 1);            

        int la = tmp.mat[0][1];                                     
        int lb = tmp.mat[1][1];
        int ans = ((a * la) + ( b * lb))% m;                        //f(n)

        printf("%d\n", ans);
    }
    return 0;
}

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