HDOJ 1757 – A Simple Math Problem

来源:互联网 发布:淘宝全屏店招制作 编辑:程序博客网 时间:2024/06/05 17:21

Matrix Multiplication (& Quick Power) 


Description

给出一个递推式,求f(x) 对 m 取模的结果。


Type

Matrix Multiplication

Quick Power


Analysis

很典型的矩阵乘法和快速幂的题目,需要构造 10 * 10 的矩阵。矩阵也是很经典的~

矩阵的图片没了……来个文字版的:

a0 1 0 0 0 0 0 0 0 0

a1 0 1 0 0 0 0 0 0 0

a2 0 0 1 0 0 0 0 0 0

a3 0 0 0 1 0 0 0 0 0

a4 0 0 0 0 1 0 0 0 0

a5 0 0 0 0 0 1 0 0 0

a6 0 0 0 0 0 0 1 0 0

a7 0 0 0 0 0 0 0 1 0

a8 0 0 0 0 0 0 0 0 1

a9 0 0 0 0 0 0 0 0 0


Solution

// HDOJ 1757// A Simple Math Problem// by A Code Rabbit#include <cstdio>#include <cstring>const int MAXO = 12;template <typename T>struct Matrix {    T e[MAXO][MAXO];    int o;    Matrix(int _o) { memset(e, 0, sizeof(e)); o = _o; }    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];        return res;    }    Matrix operator%(int mod) {        for (int i = 0; i < o; i++)            for (int j = 0; j < o; j++)                e[i][j] %= mod;        return *this;    }};template <typename T>T QuickPower(T radix, int exp, int mod) {    T res = radix;    exp--;    while (exp) {        if (exp & 1) res = res * radix % mod;        exp >>= 1;        radix = radix * radix % mod;    }    return res;}int k, m;int a[MAXO];const int F[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };int main() {    while (scanf("%d%d", &k, &m) != EOF) {        // Input.        for (int i = 0; i < 10; i++)            scanf("%d", &a[i]);        // Solve.        if (k < 10) {            printf("%d\n", k % m);            continue;        }        Matrix<long long> one(10);        for (int i = 0; i < one.o; i++)            one.e[i][0] = a[i];        for (int i = 0; i < one.o - 1; i++)            one.e[i][i + 1] = 1;        Matrix<long long> ans = QuickPower(one, k - 9, m);        // Compute ans output.        int sum = 0;        for (int i = 0; i < 10; i++)            sum += F[i] * ans.e[i][0];        printf("%d\n", sum % m);    }    return 0;}