牛客等级之题N2(8.13场)斐波那契前n项平方和

题目链接:https://ac.nowcoder.com/acm/contest/7047/A

有收获?希望老铁们来个三连击,给更多的人看到这篇文章

1、给俺点个赞呗,可以让更多的人看到这篇文章,顺便激励下我,嘻嘻。

2、老铁们,关注我的原创微信公众号「Grand Theft Algorithm」,专注于写算法题解 + 计算机基础知识

分析

数学归纳法可得:
S n = f n ( f n + f n 1 ) S_n = f_n * (f_n + f_{n - 1})
用矩阵快速幂即可:
[ f n f n 1 ] [ 1 1 1 0 ] = [ f n + 1 f n ] \begin{bmatrix} f_n&f_{n-1} \end{bmatrix} * \begin{bmatrix} 1&1\\ 1&0 \end{bmatrix} =\begin{bmatrix} f_{n+1}&f_{n} \end{bmatrix}

代码

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int M = 1e9 + 7;

struct mat {
    ll a[2][2];
};

mat mut(mat x, mat y) {
    mat res;
    memset(res.a,0,sizeof(res.a));
    for(int i = 0; i < 2; i++) {
        for(int j = 0; j < 2; j++) {
            for(int k = 0; k < 2; k++) {
                res.a[i][j]=(res.a[i][j] + x.a[i][k] * y.a[k][j]) % M;
            }
        }
    }
    return res;
}

void quick(ll n) {
    mat c, res;
    c.a[0][0]=1;
    c.a[0][1]=1;
    c.a[1][0]=1;
    c.a[1][1]=0;
    memset(res.a, 0, sizeof(res.a));
    for(int i = 0; i < 2; i++) {
        res.a[i][i] = 1;
    }
    while(n) {
        if(n & 1) {
            res = mut(res, c);
        }
        c = mut(c, c);
        n >>= 1;
    }
    printf("%lld\n",((res.a[0][1] % M) * (res.a[0][1] % M + res.a[1][1] % M)) % M);
}

int main() {
    ll n;
    cin >> n;
    quick(n);
    return 0;
}
}

有收获?希望老铁们来个三连击,给更多的人看到这篇文章

1、给俺点个赞呗,可以让更多的人看到这篇文章,顺便激励下我,嘻嘻。

2、老铁们,关注我的原创微信公众号「Grand Theft Algorithm」,专注于写算法题解 + 计算机基础知识

猜你喜欢

转载自blog.csdn.net/weixin_42396397/article/details/107972138