杭电_hdu1757_矩阵解线性方程_快速幂乘

来源:互联网 发布:芒果tv网络连接失败 编辑:程序博客网 时间:2024/05/03 19:33

/* 


f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10)
构造的矩阵是:

|0   1   0 ..... 0|     |f0|    |f1 |
|0   0   1   0 . 0|     |f1|    |f2 |
|................1|  *  |..| =  |...|
|a9  a8  .......a0|     |f9|    |f10|

*/

#include<iostream>
#include<cstdio>
#include<cmath>

struct mat
{
    int m[10][10];
};
int n,k;

mat product(mat a,mat b)         //矩阵相乘
{
    mat c;
    memset(c.m,0,sizeof(c.m));
    int i,j,l;
    for(i=0;i<10;i++)
        for(j=0;j<10;j++)
        {
            for(l=0;l<10;l++)
                c.m[i][j]+=a.m[i][l]*b.m[l][j]%k;
            c.m[i][j]%=k;
        }
        return c;
}

mat div(mat a,int x)   //快速幂乘
{
    if(x==1)
        return a;
    else if(x&1)
        return product(div(a,x-1),a);
    else
    {
        mat temp=div(a,x>>1);
        return product(temp,temp);
    }
}

int main()
{
    mat a;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        if(n<10)
        {
            printf("%d",n%k);
            continue;
        }
        int i,j;
        for(i=9;i>=0;i--)
            scanf("%d",&a.m[9][i]);
        for(i=0;i<9;i++)
            for(j=0;j<10;j++)
                if(i==j-1)
                    a.m[i][j]=1;
                else
                    a.m[i][j]=0;
                mat b=div(a,n-9);
                int ans=0;
                for(i=0;i<10;i++)
                    ans+=b.m[9][i]*i%k;
                printf("%d/n",ans%k);
    }
    return 0;
}

原创粉丝点击