中南林业大学11th K 序列求和 矩阵快速幂

题目描述 

定义S(n) = 12 + 22 + … + n2,输出S(n) % 1000000007。

注意:1 < n < 1e18。

输入描述:

多组输入,输入直到遇到EOF为止;

第一行输入一个正整数n。

输出描述:

输出S(n) % 1000000007的结果。
示例1

输入

1
2
1000

输出

1
5
333833500


但是也可以用矩阵快速幂来做

递推公式 : S(n) = S(n-1) * n^2

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9+7;
const int maxn = 4;
const ll Tmaze[][4] = {
    1,1,0,0,
    0,1,2,1,
    0,0,1,1,
    0,0,0,1
};
const ll Amaze[][4] = {
    0,0,0,0,
    0,0,0,1,
    0,0,0,1,
    0,0,0,1,
};
struct Matrix 
{
    ll maze[maxn][maxn];
    int len;
    Matrix(int lens = 0):len(lens){ memset(maze,0,sizeof(maze)); };
    // Maxrix():len(0) { memset(maze,0,sizeof(maze)); };
    void einit() {
        for(int i=0;i<len;i++) for(int j=0;j<len;j++) maze[i][j] = (i==j);
    }
    void pinit() {
        memcpy(maze,Tmaze,sizeof(Tmaze));
    }
    void ainit() {
        memcpy(maze,Amaze,sizeof(Amaze));
    };
    void output() {
        for(int i=0;i<len;i++) {
            for(int j=0;j<len;j++) {
                printf("%lld ",maze[i][j]);
            }
            printf("\n");
        }
    }
    void operator = (const Matrix &a) {
         memcpy(maze,a.maze,sizeof(a.maze));
         len = a.len; 
    }
    Matrix operator * (const Matrix &a) const{
        Matrix ans(len);
        for(int k=0;k<len;k++) {
            for(int i=0;i<len;i++) if(maze[i][k]) {
                for(int j=0;j<len;j++) if(a.maze[k][j]) {
                    ans.maze[i][j] = (ans.maze[i][j] + maze[i][k] * a.maze[k][j] % mod) % mod;
                }
            }
        }
        return ans;
    }
    Matrix operator ^ (ll b) {
        Matrix ans(len),a(len);
        a = *this;
        ans.einit();
        while(b) {
            if(b&1) ans = ans * a;
            a = a * a;
            b >>= 1;
        }
        return ans;
    }
};
int main()
{
    ll n;
    while(~scanf("%lld",&n))
    {
        Matrix res(4),pow(4);
        res.ainit();pow.pinit();
        //res.output();pow.output();
        pow = pow ^ n;
        res = pow * res;
        printf("%lld\n",res.maze[0][3]); 
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_38013346/article/details/80412954