蓝桥集训之斐波那契数列

蓝桥集训之斐波那契数列

  • 核心思想:矩阵乘法

    • 将原本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;
  }
相关推荐
黎阳之光几秒前
全域实景立体管控:数字孪生与视频孪生技术体系白皮书
大数据·人工智能·算法·安全·数字孪生
88号技师1 小时前
2026年4月一区SCI-狒狒优化算法Baboon optimization algorithm-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
凯瑟琳.奥古斯特1 小时前
BFS解力扣1654最短跳跃次数
数据结构·算法·广度优先
sg_knight1 小时前
第一次用 OpenClaw,我让它 3 分钟写了个小工具
算法·llm·agent·ai编程·openclaw
m0_629494731 小时前
LeetCode 热题 100-----23.反转链表
数据结构·算法·leetcode·链表
炸膛坦客1 小时前
嵌入式 - 数据结构与算法:(1-10)排序算法 - 冒泡排序(Bubble Sort)
算法·排序算法
Hello eveybody1 小时前
介绍一下动态树LCT(Python)
开发语言·python·算法
不穿铠甲的穿山甲1 小时前
MMR最大边际相关性
算法
handler011 小时前
速通蓝桥杯省一:二分算法
c语言·开发语言·c++·笔记·算法·职场和发展·蓝桥杯
炽烈小老头1 小时前
【 每天学习一点算法 2026/05/08】最小覆盖子串
学习·算法