矩阵快速幂!
2024-06-22 20:16:31
发布于:上海
49阅读
0回复
0点赞
显然这题可以用矩阵快速幂完成,起始矩阵是斐波那契数列前两项 ,转移矩阵是 ,即矩阵递推式 中各项的系数。时间复杂度是 的,跑得飞快,加上模数后 在 范围都能轻松跑过。
#include <cstdio>
#include <algorithm>
#include <memory.h>
using namespace std;
inline long long read(){
long long x=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-') w=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9'){
x=(x<<3)+(x<<1)+(ch^48);
ch=getchar();
}
return x*w;
}
void write(long long x){
if(x<0) putchar('-'),x=-x;
if(x>9) write(x/10);
putchar((x%10)^48);
}
struct mat{
long long a[3][3];
};
mat mul(mat& a,mat& b){
mat c;
memset(c.a,0,sizeof(c.a));
for(int k=1;k<=2;k++)
for(int i=1;i<=2;i++)
for(int j=1;j<=2;j++)
c.a[i][j]=c.a[i][j]+a.a[i][k]*b.a[k][j];
return c;
}
int main(){
long long n=read();
if(n<=2){
putchar(49);putchar(10);return 0;
}
mat a;
#define a a.a
a[1][1]=1;a[1][2]=1;
a[2][1]=1;a[2][2]=0;
#undef a
mat ans;
memset(ans.a,0,sizeof(ans.a));
ans.a[1][1]=1;ans.a[2][2]=1;
do{
if(n&1) ans=mul(ans,a);
a=mul(a,a);n>>=1;
}while(n);
write(ans.a[2][1]);putchar(10);
return 0;
}
全部评论 3
你说得对,但是真正需要这个题解的地方在绿题
2024-08-13 来自 湖南
0你说得对,但是这是一篇乐子题解
2024-08-13 来自 浙江
0桂霞😡😡😡
2024-08-13 来自 湖南
0在吗,帮我看看我的矩阵为什么错(链接
#include <iostream> #include <cstdio> #define int unsigned long long using namespace std; const int mod = 1e9+7; struct node{ int fib[2][2] = {{0, 0}, {0, 0}}; node operator * (const node &b) const{ node temp; for(int i = 0; i < 2; i++){ for(int j = 0; j < 2; j++){ for(int k = 0; k < 2; k++) temp.fib[i][j] = (temp.fib[i][j] + fib[i][k] * b.fib[k][j] % mod) % mod; } }return temp; } }a, b; signed main(){ a.fib[0][0] = a.fib[1][0] = a.fib[0][1] = 1; b.fib[0][0] = b.fib[1][1] = 1; int n; cin >> n; for(int i = 1; i <= n; i++){ b = b * a; } cout << b.fib[0][1]; return 0; }
2024-08-15 来自 湖南
0
6
2024-07-16 来自 广东
0d
2024-06-22 来自 上海
0
有帮助,赞一个