HDOJ 2256 - Problem of Precision

Matrix Multiplication (& Quick Power) 


Description

求图中那个有根号,有幂,有下取整的变态公式的值。


Type

Matrix Multiplication

Quick Power


Analysis

这题首先要注意不能将一个实数取模,即使你把它拆成整数部分和小数部分。

要用数学方法来解这题,我是解释不来的,所以这里引用一下牛人的推导:

推倒~之后,我们就可以利用矩阵乘法去求Xn,然后计算出梦寐以求的 ans 了。


Solution

// HDOJ 2256
// Problem of Precision
// by A Code Rabbit

#include <cstdio>
#include <cstring>

const int MAXO = 4;
const int MOD = 1024;

template <typename T>
struct Matrix {
    T e[MAXO][MAXO];
    int o;
    Matrix(int x) { memset(e, 0, sizeof(e)); o = x; }
    Matrix operator*(const Matrix& one) {
        Matrix res(o);
        for (int i = 0; i < o; i++) {
            for (int j = 0; j < o; j++) {
                for (int k = 0; k < o; k++)
                    res.e[i][j] += e[i][k] * one.e[k][j];
                res.e[i][j] %= MOD;
            }
        }
        return res;
    }
    Matrix operator*=(const Matrix& one) { return *this = *this * one; }
};

template <typename T>
T QuickPower(T radix, int exp) {
    T res = radix;
    exp--;
    while (exp) {
        if (exp & 1) res *= radix;
        exp >>= 1;
        radix *= radix;
    }
    return res;
}

int n;
Matrix<int> radix(2);

int main() {
    int tot_case;
    scanf("%d", &tot_case);
    while (tot_case--) {
        // Input.
        scanf("%d", &n);       
        // Solve.
        radix.e[0][0] = 5;
        radix.e[0][1] = 2;
        radix.e[1][0] = 12;
        radix.e[1][1] = 5;
        Matrix<int> ans = QuickPower(radix, n - 1);
        // Compute and output.
        int x_n = (5 * ans.e[0][0] + 2 * ans.e[1][0]) % MOD;
        printf("%d\n", (x_n * 2 - 1) % MOD);
    }

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值