题目链接http://poj.org/problem?id=3070
涨姿势了原来斐波那契还可以用矩阵去算。也当是知识积累,同时更新自己的模板库
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> vec;
typedef vector<vec> mat;
typedef long long LL;
const int N = 10000;
mat mul(mat a,mat b) //矩阵乘法
{
mat c(a.size(),vec(b[0].size()));
for(int i=0; i<a.size(); i++)
{
for(int k=0; k<b.size(); k++)
{
for(int j=0; j<b[0].size(); j++)
c[i][j] = ( c[i][j] + a[i][k] * b[k][j] ) % N;
}
}
return c;
}
mat solve_pow(mat a,int n) //快速幂
{
mat b(a.size(),vec(a.size()));
for(int i=0; i<a.size(); i++)
b[i][i]=1;
while(n>0)
{
if(n & 1)
b=mul(b,a);
a=mul(a,a);
n >>= 1;
}
return b;
}
LL n;
int main()
{
while(cin>>n,n!=-1)
{
mat a(2,vec(2));
a[0][0]=1,a[0][1]=1;
a[1][0]=1,a[1][1]=0;
a=solve_pow(a,n);
printf("%d\n",a[1][0]);
}
return 0;
}

本文介绍了一种使用矩阵快速幂算法高效计算斐波那契数的方法,并提供了完整的C++代码实现。该方法避免了传统递归或迭代算法的效率瓶颈,特别适合于计算较大的斐波那契数。
4110

被折叠的 条评论
为什么被折叠?



