hdu 4990 Reading comprehension 矩阵快速幂

矩阵的递推关系式为

[ans200]=[4011]n/21[2200]

如果n为奇数,则ans=ans*2+1

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=10;
int n=2;
ll m;

struct Mat
{
    ll mat[N][N];
};

Mat operator * (Mat a, Mat b)
{
    Mat c;
    memset(c.mat, 0, sizeof(c.mat));
    int i, j, k;
    for(k = 0; k < n; ++k)
    {
        for(i = 0; i < n; ++i)
        {
            for(j = 0; j < n; ++j)
            {
                c.mat[i][j] += a.mat[i][k] * b.mat[k][j];
                c.mat[i][j]=c.mat[i][j]%m;
            }
        }
    }
    return c;
}

Mat operator ^ (Mat a, int k)
{
    Mat c;
    int i, j;
    for(i = 0; i < n; ++i)
        for(j = 0; j < n; ++j)
            c.mat[i][j] = (i == j);    //初始化为单位矩阵

    for(; k; k >>= 1)
    {
        if(k&1) c = c*a;
        a = a*a;
    }
    return c;
}

int main()
{
    int i,j;
    ll k;
    while(~scanf("%lld%lld",&k,&m))
    {
        if(k==1) printf("%d\n",1%m);
        else if(k==2) printf("%d\n",2%m);
        else if(k==3) printf("%d\n",5%m);
        else
        {
            Mat a,b;
            memset(a.mat,0,sizeof(a.mat));
            a.mat[0][0]=4;
            a.mat[0][1]=1;
            a.mat[1][0]=0;
            a.mat[1][1]=1;
            a=a^(k/2-1);
            memset(b.mat,0,sizeof(b.mat));
            b.mat[0][0]=2;
            b.mat[1][0]=2;
            ll ans=0;
            b=a*b;
            if(k&1) ans=(b.mat[0][0]*2+1)%m;
            else ans=b.mat[0][0];
            printf("%lld\n",ans);
        }
    }
    return 0;
}

你可能感兴趣的:(hdu 4990 Reading comprehension 矩阵快速幂)