1. 程式人生 > >HDU-1757 A Simple Math Problem(矩陣快速冪)

HDU-1757 A Simple Math Problem(矩陣快速冪)

題目

A Simple Math Problem

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 6512    Accepted Submission(s): 3996  

Problem Description

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.

Input

The problem contains mutiple test cases.Please process to the end of file. In each case, there will be two lines. In the first line , there are two positive integers k and m. ( k<2*10^9 , m < 10^5 ) In the second line , there are ten integers represent a0 ~ a9.

Output

For each case, output f(k) % m in one line.

Sample Input

10 9999 1 1 1 1 1 1 1 1 1 1 20 500 1 0 1 0 1 0 1 0 1 0

Sample Output

45 104

題目連結:戳這裡

思路

k的值比較大,所以遞推是不行的。

那麼就考慮矩陣快速冪。

根據 公式構造矩陣,然後直接模板就ok了。

程式碼

#include<cstdio>

using namespace std;

const int maxn = 10;
int k,MOD;
#define mod(x) ((x)%MOD)

struct Matrix{
    int a[maxn][maxn];
    void init(){
        for(int i=0;i < maxn;i++){
            for(int j=0;j < maxn;j++){
                a[i][j] = 0;
            }
        }
    }
};

Matrix mul(Matrix A,Matrix B){
    Matrix res;
    res.init();
    for(int i=0;i < maxn;i++){
        for(int j=0;j < maxn;j++){
            for(int k=0;k < maxn;k++){
                res.a[i][j] = mod(res.a[i][j] + mod(A.a[i][k]*B.a[k][j]));
            }
        }
    }
    return res;
}

Matrix poww(Matrix A,Matrix B,int n){
    Matrix res = B;
    while(n){
        if(n&1)res = mul(res,A);
        A = mul(A,A);
        n >>= 1;
    }
    return res;
}

void outPut(Matrix A){
    for(int i=0;i < maxn;i++){
        for(int j=0;j < maxn;j++){
            printf("%d ",A.a[i][j]);
        }
        printf("\n");
    }
}

int main(){
    while(~scanf("%d%d",&k,&MOD)){
        Matrix A,B;
        A.init();
        B.init();
        for(int i=9;i >= 0;i--){
            A.a[0][9-i] = i;
        }
        for(int i=0;i <= 9;i++){
            scanf("%d",&B.a[i][0]);
        }
        for(int i=0;i < 9;i++){
            B.a[i][i+1] = 1;
        }
        A = poww(B,A,k-9);
        printf("%d\n",A.a[0][0]);
    }
    return 0;
}