SDNU1068(矩阵快速幂模板)

#include<bits/stdc++.h>
using namespace std;
const int maxn=3;
const int mod=1000000007;
struct mat
{
    long long int m[maxn][maxn];
} ans;
mat mul(mat A,mat B)
{
    mat tmp;
    for(int i=0; i<maxn; ++i)
        for(int j=0; j<maxn; ++j)
            tmp.m[i][j]=0;
    for(int i=1; i<maxn; ++i)
        for(int j=1; j<maxn; ++j)
            for(int k=1; k<maxn; ++k)
                tmp.m[i][j]=(tmp.m[i][j]+(A.m[i][k])*(B.m[k][j])%mod)%mod;
    return tmp;
}
mat quickpow(mat res,long long int N)
{
    for(int i=1; i<maxn; ++i)
        for(int j=1; j<maxn; ++j)
        {
            if(i==j)
                ans.m[i][j]=1;
            else
                ans.m[i][j]=0;
        }
    while(N)
    {
        if(N&1)
            ans=mul(ans,res);
        res=mul(res,res);
        N>>=1;
    }
    return ans;
}
int main()
{
    mat res;
    for(int i=1; i<maxn; ++i)
        for(int j=1; j<maxn; ++j)
        {
            if(i==j&&i==2)
                res.m[i][j]=0;
            else
                res.m[i][j]=1;
        }
    long long int n;
    scanf("%lld",&n);
    res=quickpow(res,n);
    printf("%lld\n",res.m[1][2]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41658955/article/details/87188661