蓝桥集训之斐波那契数列

蓝桥集训之斐波那契数列

  • 核心思想:矩阵乘法

    • 将原本O(n)的递推算法优化为O(log2n)

    • 构造1x2矩阵f和2x2矩阵a

    • 发现f(n+1) = f(n) * a

      • 则f(n+1) = f(1) * an
      • 可以用快速幂优化
cpp 复制代码
  #include <iostream>
  #include <cstring>
  #include <algorithm>
  
  using namespace std;
  const int MOD = 10000;
  int f[2];
  int a[2][2];
  int n;
  
  void mul1()
  {
      int res[2];  //res = res*a 求1x2矩阵
      memset(res,0,sizeof res);
      for(int i=0;i<2;i++)
          for(int j=0;j<2;j++)
              res[i] = (res[i] + f[j] * a[j][i]) %MOD;  //计算f*a
              
      memcpy(f,res,sizeof f);
  }
  void mul2()
  {
      int res[2][2];  //a = a*a 求2x2矩阵
      memset(res,0,sizeof res);
      for(int i=0;i<2;i++)
          for(int j=0;j<2;j++)
              for(int k=0;k<2;k++)
                  res[i][j] = (res[i][j] + a[i][k] * a[k][j])%MOD;  //计算a*a
      
      memcpy(a,res,sizeof a);
  }
  void qmi(int n)
  {
      while (n)  //快速幂优化
      { 
          if(n&1) mul1();  //res = res*a%MOD
          mul2();  //a = a*a%MOD
          n>>=1;
      }
  }
  int main()
  {
      while(cin>>n , n!=-1)
      {
          f[0] = 0,f[1] = 1;  //初始化第0 1项
          a[0][0] = 0,a[0][1] = 1,a[1][0] = 1,a[1][1] = 1;  //初始化a矩阵
          qmi(n); 
          cout<<f[0]<<endl;
      }
      return 0;
  }
相关推荐
wuweijianlove1 天前
算法性能的渐近与非渐近行为对比的技术4
算法
_dindong1 天前
cf1091div2 C.Grid Covering(数论)
c++·算法
AI成长日志1 天前
【Agentic RL】1.1 什么是Agentic RL:从传统RL到智能体学习
人工智能·学习·算法
黎阳之光1 天前
黎阳之光:视频孪生领跑者,铸就中国数字科技全球竞争力
大数据·人工智能·算法·安全·数字孪生
skywalker_111 天前
力扣hot100-3(最长连续序列),4(移动零)
数据结构·算法·leetcode
6Hzlia1 天前
【Hot 100 刷题计划】 LeetCode 17. 电话号码的字母组合 | C++ 回溯算法经典模板
c++·算法·leetcode
wfbcg1 天前
每日算法练习:LeetCode 209. 长度最小的子数组 ✅
算法·leetcode·职场和发展
_日拱一卒1 天前
LeetCode:除了自身以外数组的乘积
数据结构·算法·leetcode
计算机安禾1 天前
【数据结构与算法】第36篇:排序大总结:稳定性、时间复杂度与适用场景
c语言·数据结构·c++·算法·链表·线性回归·visual studio
SatVision炼金士1 天前
合成孔径雷达干涉测量(InSAR)沉降监测算法体系
算法