蓝桥集训之斐波那契数列

蓝桥集训之斐波那契数列

  • 核心思想:矩阵乘法

    • 将原本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;
  }
相关推荐
Coder_Shenshen1 小时前
西门子S7CommPlus协议鉴权算法原理与流程详解
网络·后端·算法
硕风和炜1 小时前
【LeetCode: 2492. 两个城市间路径的最小分数 + DFS】
java·算法·leetcode·深度优先·dfs·bfs·并查集
我是一颗柠檬2 小时前
【Java项目技术亮点】加权轮询负载均衡算法
java·算法·负载均衡
灯厂码农3 小时前
C语言动态内存分配完全指南(malloc、calloc、realloc、free)
java·c语言·算法
凯瑟琳.奥古斯特4 小时前
K次取反最大化数组和解法(力扣1005)
开发语言·c++·算法·leetcode·职场和发展
Jerry4 小时前
LeetCode 203. 移除链表元素
算法
地平线开发者4 小时前
征程 6 | 工具链 QAT ObserverBase 源码解析
算法
地平线开发者5 小时前
【地平线 征程 6 工具链进阶教程】QAT 训练常见问题和排查
算法
地平线开发者5 小时前
征程 6 | 直方图量化配置与校准实例
算法