HDU1757-A Simple Math Problem(矩阵快速幂)

来源:互联网 发布:鲁班软件 北京 编辑:程序博客网 时间:2024/05/16 02:05

题目链接


题意:求出f(k) % m

思路:f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10),所以可以得到一个矩阵 
(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) 
(1, 0, 0, 0, 0, 0, 0, 0, 0, 0) 
(0, 1, 0, 0, 0, 0, 0, 0, 0, 0) 
(0, 0, 1, 0, 0, 0, 0, 0, 0, 0) 
(0, 0, 0, 1, 0, 0, 0, 0, 0, 0) 
(0, 0, 0, 0, 1, 0, 0, 0, 0, 0) 
(0, 0, 0, 0, 0, 1, 0, 0, 0, 0) 
(0, 0, 0, 0, 0, 0, 1, 0, 0, 0) 
(0, 0, 0, 0, 0, 0, 0, 1, 0, 0) 
(0, 0, 0, 0, 0, 0, 0, 0, 1, 0)* 
|f(x - 1), f(x - 2), f(x - 3), f(x - 4), f(x - 5), f(x - 6), f(x - 7), f(x - 8), f(x - 9), f(x - 10)| = 
|f(x), f(x - 1), f(x - 2), f(x - 3), f(x - 4), f(x - 5), f(x - 6), f(x - 7), f(x - 8), f(x - 9)| 
通过矩阵快速幂求解。

代码:

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>using namespace std;typedef __int64 ll;const int N = 10;ll k, m;struct mat{    ll s[N][N];    mat() {        sizeof(s, 0, sizeof(s));    }    mat operator * (const mat& c) {        mat ans;         memset(ans.s, 0, sizeof(ans.s));        for (int i = 0; i < N; i++)             for (int j = 0; j < N; j++)                for (int k = 0; k < N; k++)                    ans.s[i][j] = (ans.s[i][j] + s[i][k] * c.s[k][j]) % m;        return ans;    }};mat state, tmp;void init() {    for (int i = 0; i < 10; i++)        tmp.s[i][0] = 9 - i;    for (int i = 0; i < 10; i++)         scanf("%I64d", &state.s[0][i]);    for (int i = 0; i < 10; i++)        for (int j = 0; j < 10; j++)            if (i - 1 == j)                state.s[i][j] = 1;}mat pow_mod(ll k) {    if (k == 1)        return state;    mat a = pow_mod(k / 2);    mat ans = a * a;    if (k % 2 == 1)        ans = ans * state;    return ans;}int main() {    while (scanf("%I64d%I64d", &k, &m) != EOF) {        if (k < 10)             printf("%I64d\n", k % m);         else {            init();            mat ans = pow_mod(k - 9);            ans = ans * tmp;            printf("%I64d\n", ans.s[0][0]);        }     }    return 0;}


0 0