中南林业大学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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值