裴波那契数列平方和-矩阵运算 代码 连接

给定N,求f12+f22+···+fn^2

矩阵运算的裸题,直接套模版即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

#include<cstring>
#include<iostream>
using namespace std;
long long n,Ans=1,CK=1000000007;
struct {
long long a[3][3];
matrix(){memset(a,0,sizeof a);}
void operator *=(const matrix &x){
matrix ans=matrix();
for (int i=1;i<=2;i++)
for (int j=1;j<=2;j++)
ans.a[i][j]=((a[i][1]*x.a[1][j])%CK+(a[i][2]*x.a[2][j])%CK)%CK;
*this=ans;
}
void clear(){
a[1][1]=a[1][2]=a[2][1]=1; a[2][2]=0;
}
}ans=matrix(),x=matrix();
inline void work(long long k){
long long p=k;
while (p){
if (p&1) ans*=x;
x*=x; p/=2;
}
Ans=(ans.a[2][1]*ans.a[1][1])%CK;
}
int main(){
freopen("fibsqr.in","r",stdin);
freopen("fibsqr.out","w",stdout);
cin>>n;
ans.clear(); x.clear(); work(n-1);
printf("%lldn",Ans);
return 0;
}

连接

COGS