其他分享
首页 > 其他分享> > [51nod 1126] 求递推序列的第N项 - 矩阵乘法

[51nod 1126] 求递推序列的第N项 - 矩阵乘法

作者:互联网

#include <bits/stdc++.h>
using namespace std;

#define int long long
const int mod = 7;

struct matrix {
    int a[5][5]={};
    int n,m;
};

matrix I(int n) {
    matrix ret;
    ret.n=n;
    ret.m=n;
    for(int i=1;i<=n;i++) ret.a[i][i]=1;
    return ret;
}

matrix operator * (matrix a, matrix b) {
    matrix ret;
    ret.n = a.n;
    ret.m = b.m;
    for(int i=1;i<=ret.n;i++) {
        for(int j=1;j<=ret.m;j++) {
            for(int k=1;k<=a.m;k++) {
                ret.a[i][j] += a.a[i][k] * b.a[k][j];
                ret.a[i][j] %= mod;
                ret.a[i][j] += mod;
                ret.a[i][j] %= mod;
            }
        }
    }
    return ret;
}

matrix qpow(matrix p, int q) {
    return ((q&1)?p:I(2)) * (q?qpow(p*p,q/2):I(2));
}

signed main() {
    matrix T;
    T.n=2; T.m=2;
    int a,b,n;
    cin>>a>>b>>n;
    T.a[1][1]=a; T.a[1][2]=b;
    T.a[2][1]=1;
    T=qpow(T,n-2);
    matrix A;
    A.n=2; A.m=1;
    A.a[1][1]=1; A.a[2][1]=1;
    if(n==1) cout<<1<<endl;
    else cout<<(T*A).a[1][1];
}

标签:std,long,const,matrix,51nod,1126,int,ret,递推
来源: https://www.cnblogs.com/mollnn/p/12359066.html