The 2019 Asia Nanchang First Round Online Programming Contest-H-The Nth Item

矩阵快速幂的应用
由关系式有:
F (n) =3 *F(n - 1) + 2 * F(n - 2)
F(n - 1) =1 * F(n - 1) + 0 * F(n - 2)
则选取矩阵(b):
b[1][1] = 3;
b[1][2] = 2;
b[2][1] = 1;
b[2][2] = 0;

代码:

    #include
    using namespace std;
    const int mod = 998244353;
    typedef long long ll;
    struct mat {
       ll a[3][3];
    } ans, base;
    void init() {
        memset(ans.a, 0, sizeof(ans.a));
        ans.a[1][1] = 1;
        memset(base.a, 0, sizeof(base.a));
        base.a[1][1] = 3;
        base.a[1][2] = 2;
        base.a[2][1] = 1;
     } //初始化矩阵
     mat yunsuan(mat j1, mat j2) {
        mat m;
        m.a[1][1] = ((j1.a[1][1]%mod)*(j2.a[1][1]%mod)%mod+(j1.a[1][2]%mod)*(j2.a[2][1]%mod)%mod)%mod;
        m.a[1][2] = ((j1.a[1][1]%mod)*(j2.a[1][2]%mod)%mod+(j1.a[1][2]%mod)*(j2.a[2][2]%mod)%mod)%mod;
        m.a[2][1] = ((j1.a[2][1]%mod)*(j2.a[1][1]%mod)%mod+(j1.a[2][2]%mod)*(j2.a[2][1]%mod)%mod)%mod;
        m.a[2][2] = ((j1.a[2][1]%mod)*(j2.a[1][2]%mod)%mod+(j1.a[2][2]%mod)*(j2.a[2][2]%mod)%mod)%mod;
        return m;
     } //矩阵乘法
    mappp;
    ll ksm(ll n) {
        if(pp.count(n)) return pp[n]; //已经计算过则直接返回值
        init(); //别忘记 忘了就是个WA
        ll num = n;
        while(n) {
	       if(n & 1) ans = yunsuan(ans, base);
	       base = yunsuan(base, base);
	       n >>= 1; 
         }
         return pp[num] = ans.a[1][1] % mod; //用map记录
    }
    const int maxn = 1e7 + 5;
    ll rec[maxn];
    int main() {
        ll Q,N,num,q;
        cin >> Q >> N;
        q = N;
        for(int i=0; i

总结:
矩阵快速幂的程序是固定的模板,变化的只是矩阵,即上面的ans和base;
所以我们只需要 由递归式得到base(相当于Aa^b中的a),由初值得到ans(Aa ^ b中的A);

你可能感兴趣的:(The 2019 Asia Nanchang First Round Online Programming Contest-H-The Nth Item)