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

http://acm.hdu.edu.cn/showproblem.php?pid=1757
題目大意:input 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 .
輸入k和m,求f(k)%m,a0~a9是用戶輸入的。
解題思路:因爲k的範圍是2*10^9而時間只有1秒,所以用題目上給的遞推公式肯定會超時,所以這裏我們可以構造一個矩陣,通過矩陣快速冪來求。
根據題意可構造如下矩陣:
這裏寫圖片描述
而根據題目已知條件f(0)~f(9)等於0~9,其餘直接用矩陣快速冪即可。
CODE:

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
struct Matrix
{
    int m[10][10];
};
ll k,m;
Matrix Init(int a[])///初始化所構造的矩陣
{
    int b[10][10] = {a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],
                     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,};
    Matrix s;
    for(int i=0;i<10;i++)
        for(int j=0;j<10;j++)
            s.m[i][j] = b[i][j];
   return s;
}
Matrix Mult(Matrix a,Matrix b)///計算兩個矩陣相乘
{
    Matrix temp;
    for(int i=0;i<10;i++)
        for(int j=0;j<10;j++)
            temp.m[i][j] = 0;
    for(int i=0;i<10;i++)
        for(int j=0;j<10;j++)
        for(int k=0;k<10;k++)
            temp.m[i][j] = (temp.m[i][j] + a.m[i][k]*b.m[k][j])%m;
    return temp;
}

Matrix QuickPower(Matrix a,ll k)///矩陣快速冪
{
    Matrix ans,res;
    res = a;
    for(int i=0;i<10;i++)
        for(int j=0;j<10;j++)
           i==j? ans.m[i][j]=1:ans.m[i][j]=0;
    while(k){
        if(k&1)
            ans = Mult(ans,res);
        res = Mult(res,res);
        k>>=1;
    }
    return ans;
}
int main()
{
    int a[10];
    while(~scanf("%lld %lld",&k,&m)){
        for(int i=0;i<10;i++)
            scanf("%d",&a[i]);
        Matrix s = Init(a);
        if(k<10){
            printf("%d\n",k%m);
            continue;
        }
        Matrix temp = QuickPower(s,k-9);
        ll ans = ((temp.m[0][0]*9)%m+(temp.m[0][1]*8)%m+(temp.m[0][2]*7)%m+(temp.m[0][3]*6)%m+(temp.m[0][4]*5)%m+(temp.m[0][5]*4)%m+(temp.m[0][6]*3)%m+(temp.m[0][7]*2)%m+(temp.m[0][8]*1)%m+(temp.m[0][9]*0)%m)%m;
        ///根據計算矩陣的方法算出f(k)
        printf("%lld\n",ans);
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章