蓝桥集训之斐波那契数列
- 
核心思想:矩阵乘法
- 
将原本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;
  }