码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-08-30 12:42:49      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   ar   for   2014   

题目链接


题意:求出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;
}


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

标签:style   blog   http   color   os   io   ar   for   2014   

原文地址:http://blog.csdn.net/u011345461/article/details/38942887

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!