[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];
}
上一篇:C语言学习笔记—P29(<C语言高阶>+自定义类型:结构体,枚举,联合<1>+题例+图解)


下一篇:51nod 1254 最大子段和 V2