Another kind of Fibonacci(hdu3306)矩阵快速幂

矩阵的快速幂直接套模板就行,关键在于如何构造矩阵。矩阵的构造方法

AC代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=4;
const int Mod=10007;
struct Matrix
{
    int row,col;
    int mat[N][N];
    void init(int row,int col,bool ok=false){
        this->row=row;
        this->col=col;
        memset(mat,0,sizeof(mat));
        if(!ok) return;
        for(int i=0;i<N;i++){
            mat[i][i]=1;
        }
    }
    Matrix operator *(const Matrix& B){
        Matrix C;
        C.init(row,B.col);
        for(int k=0;k<col;k++){
            for(int i=0;i<row;i++){
                if(mat[i][k]==0) continue;
                for(int j=0;j<B.col;j++){
                    if(B.mat[k][j]==0) continue;
                    C.mat[i][j]+=(mat[i][k]%Mod)*(B.mat[k][j]%Mod);
                    C.mat[i][j]=C.mat[i][j]%Mod;
                }
            }
        }
        return C;
    }
    Matrix pow(int n){
        Matrix B,A=*this;
        B.init(row,col,1);
        while(n){
            if(n&1) B=B*A;
            A=A*A;
            n>>=1;
        }
        return B;
    }
};
int main()
{
    int n,x,y;
    while(cin>>n>>x>>y){
        x=x%Mod;
        y=y%Mod;
        Matrix A;
        A.init(4,4);
        A.mat[0][0]=1;A.mat[0][1]=0;A.mat[0][2]=0;A.mat[0][3]=0;
        A.mat[1][0]=1;A.mat[1][1]=(x*x)%Mod;A.mat[1][2]=1;A.mat[1][3]=x;
        A.mat[2][0]=0;A.mat[2][1]=(y*y)%Mod;A.mat[2][2]=0;A.mat[2][3]=0;
        A.mat[3][0]=0;A.mat[3][1]=(2*x*y)%Mod;A.mat[3][2]=0;A.mat[3][3]=y;
        A=A.pow(n);
        Matrix B;
        B.init(1,4);
        B.mat[0][0]=1;B.mat[0][1]=1;B.mat[0][2]=1;B.mat[0][3]=1;
        B=B*A;
        cout<<B.mat[0][0]<<endl;
    }
    return 0;
}
这题一共提交八次,用long long型超时、N过大超时、G++超时……,烦死了╮(╯_╰)╭。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值