hdu 1757 A Simple Math Problem



http://acm.hdu.edu.cn/showproblem.php?pid=1757

Lele now is thinking about a simple function f(x).

If x < 10 f(x) = x.
If x >= 10 f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10);
And ai(0<=i<=9) can only be 0 or 1 .

Now, I will give a0 ~ a9 and two positive integers k and m ,and could you help Lele to caculate f(k)%m.

盗用一张图:


#include <stack>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;

int k,m,f[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
struct matrix {
    int M[12][12];
} A,E,B;

matrix multiplication(matrix a, matrix b) {
    matrix c;
    for(int i=0; i<10; i++)
        for(int j=0; j<10; j++) {
            c.M[i][j] = 0;
            for(int k=0; k<10; k++)
                c.M[i][j] += (a.M[i][k] * b.M[k][j]);
            c.M[i][j] %= m;
        }
    return c;
}

matrix quickpow(int x) {
    matrix p = E, q = A;
    while(x >= 1) {
        if(x & 1)   p = multiplication(p, q);
        x >>= 1;
        q = multiplication(q, q);
    }
    return p;
}

int main() {
//    freopen("in.txt", "r", stdin);
    for(int i=0; i<10; i++)
        for(int j=0; j<10; j++) {
            if(i == j)  E.M[i][j] = 1;
            else E.M[i][j] = 0;
        }
    while(scanf("%d%d",&k,&m) == 2) {
        for(int i=0; i<10; i++) {
            int tmp;
            scanf("%d",&tmp);
            A.M[0][i] = tmp;
        }
        for(int i=1; i<10; i++)
            for(int j=0; j<10; j++) {
                if(j == i - 1)  A.M[i][j] = 1;
                else    A.M[i][j] = 0;
            }
        if(k < 10) {
            cout << k % m << endl;
            continue;
        }
        matrix res = quickpow(k - 9);
        int ans = 0;
        for(int i=0; i<10; i++){
            ans += res.M[0][i] * (10 - i - 1);
            ans %= m;
        }
        printf("%d\n",ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值