蓝桥集训之斐波那契数列

蓝桥集训之斐波那契数列

  • 核心思想:矩阵乘法

    • 将原本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;
  }
相关推荐
Darkwanderor1 小时前
什么数据量适合用什么算法
c++·算法
zc.ovo1 小时前
河北师范大学2026校赛题解(A,E,I)
c++·算法
py有趣1 小时前
力扣热门100题之环形链表
算法·leetcode·链表
py有趣2 小时前
力扣热门100题之回文链表
算法·leetcode·链表
月落归舟3 小时前
帮你从算法的角度来认识二叉树---(二)
算法·二叉树
SilentSlot4 小时前
【数据结构】Hash
数据结构·算法·哈希算法
样例过了就是过了5 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
wsoz6 小时前
Leetcode哈希-day1
算法·leetcode·哈希算法
阿Y加油吧6 小时前
LeetCode 二叉搜索树双神题通关!有序数组转平衡 BST + 验证 BST,小白递归一把梭
java·算法·leetcode