• CodeForces 450B Jzzhu and Sequences


    矩阵快速幂。

    首先得到公式

    然后构造矩阵,用矩阵加速

    取模函数需要自己写一下,是数论中的取模。

    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<vector>
    #include<algorithm>
    using namespace std;
    
    long long MOD = 1e9 + 7;
    long long x, y;
    int n;
    
    long long mod(long long a, long long b)
    {
        if (a >= 0) return a%b;
        if (abs(a) % b == 0) return 0;
        return (a + b*(abs(a) / b + 1));
    }
    
    struct Matrix
    {
        long long A[5][5];
        int R, C;
        Matrix operator*(Matrix b);
    };
    
    Matrix X, Y, Z;
    
    Matrix Matrix::operator*(Matrix b)
    {
        Matrix c;
        memset(c.A, 0, sizeof(c.A));
        int i, j, k;
        for (i = 1; i <= R; i++)
            for (j = 1; j <= C; j++)
                for (k = 1; k <= C; k++)
                    c.A[i][j] = mod((c.A[i][j] + mod(A[i][k] * b.A[k][j], MOD)), MOD);
        c.R=R; c.C=b.C;
        return c;
    }
    
    void read()
    {
        scanf("%lld%lld%d", &x, &y, &n);
    }
    
    void init()
    {
        n = n - 1;
        Z.A[1][1] = x, Z.A[1][2] = y; Z.R = 1; Z.C = 2;
        Y.A[1][1] = 1, Y.A[1][2] = 0, Y.A[2][1] = 0, Y.A[2][2] = 1; Y.R = 2; Y.C = 2;
        X.A[1][1] = 0, X.A[1][2] = -1, X.A[2][1] = 1, X.A[2][2] = 1; X.R = 2; X.C = 2;
    }
    
    void work()
    {
        while (n)
        {
            if (n % 2 == 1) Y = Y*X;
            n = n >> 1;
            X = X*X;
        }
        Z = Z*Y;
    
        printf("%lld
    ", mod(Z.A[1][1], MOD));
    }
    
    int main()
    {
        read();
        init();
        work();
        return 0;
    }
  • 相关阅读:
    连通图是不是欧拉图
    P1127 词链 题解
    ClickHouse的JDBC连接
    ClickHouse集群搭建和使用
    ClickHouse引擎
    ClickHouse 的安装和使用
    SNMP3安装
    解决springboot打不出业务log
    如何用电脑下载微信视频号中的视频?
    【Swing】如何打开文件选择对话框,选择文件
  • 原文地址:https://www.cnblogs.com/zufezzt/p/5228899.html
Copyright © 2020-2023  润新知