HDU 5667 Sequence

指数有递推式,可以通过矩阵快速幂来求解。再用下面这公式快速幂取模即可。

(C是素数)

#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
using namespace std;

long long p,MOD;
long long a, b, c;
long long n;

struct Matrix
{
    long long A[5][5];
    int R, C;
    Matrix operator*(Matrix b);
};

Matrix X, Y, Z;

Matrix Matrix::operator*(Matrix b)
{
    Matrix c;
    memset(c.A, 0, sizeof(c.A));
    int i, j, k;
    for (i = 1; i <= R; i++)
        for (j = 1; j <= C; j++)
            for (k = 1; k <= C; k++)
                c.A[i][j] = (c.A[i][j] + (A[i][k] * b.A[k][j]) % MOD) % MOD;
    c.R = R; c.C = b.C;
    return c;
}

long long mod_exp(long long a, long long b, long long c)
{
    long long res, t;
    res = 1 % c;
    t = a % c;
    while (b)
    {
        if (b & 1) res = res * t % c;
        t = t * t % c;
        b >>= 1;
    }
    return res;
}

void init()
{
    n = n - 2;
    memset(X.A, 0, sizeof X.A);
    memset(Y.A, 0, sizeof Y.A);
    memset(Z.A, 0, sizeof Z.A);

    Z.R = 1; Z.C = 3;
    Z.A[1][1] = 1; Z.A[1][2] = 0; Z.A[1][3] = b%MOD;

    X.R = X.C = 3;
    X.A[1][1] = 1; X.A[1][2] = 0; X.A[1][3] = b%MOD;
    X.A[2][1] = 0; X.A[2][2] = 0; X.A[2][3] = 1;
    X.A[3][1] = 0; X.A[3][2] = 1; X.A[3][3] = c%MOD;


    Y.R = Y.C = 3;
    Y.A[1][1] = 1; Y.A[1][2] = 0; Y.A[1][3] = 0;
    Y.A[2][1] = 0; Y.A[2][2] = 1; Y.A[2][3] = 0;
    Y.A[3][1] = 0; Y.A[3][2] = 0; Y.A[3][3] = 1;
}

void work()
{
    while (n)
    {
        if (n % 2 == 1) Y = Y*X;
        n = n >> 1;
        X = X*X;
    }
    Z = Z*Y;
    printf("%lld\n", mod_exp(a, Z.A[1][3]+MOD, p));
}

int main()
{
    int T;
    scanf("%d", &T);
    while (T--)
    {
        scanf("%lld%lld%lld%lld%lld", &n, &a, &b, &c, &p);
        if (n == 1) printf("1\n");
        if (n == 2) printf("%lld\n", mod_exp(a, b, p));
        else
        {
            MOD = p - 1;
            init();
            work();
        }
    }
    return 0;
}

 

posted @ 2016-04-17 08:12  Fighting_Heart  阅读(291)  评论(0编辑  收藏  举报