Advertisement
maiden18

[SOLID] Matrix Exponentiation

Oct 24th, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define MOD 1000000007
  3.  
  4. using namespace std;
  5. typedef long long ll;
  6.  
  7.  
  8.  
  9.  
  10. //Square Matix Only
  11. struct Matrix{
  12.     int len; //dimension of square matrix
  13.     vector<vector<ll> >mat;
  14.     Matrix(int l)
  15.     {
  16.         len=l;
  17.         for(int i=0;i<len;i++)    {
  18.             vector<ll>tmp;
  19.             for(int j=0;j<len;j++)    tmp.push_back(0);
  20.             mat.push_back(tmp);
  21.         }
  22.     }
  23.     void setToUnitMatrix()
  24.     {
  25.         for(int i=0;i<len;i++)    {
  26.             mat[i][i]=1;
  27.         }
  28.     }
  29. };
  30.  
  31.  
  32.  
  33. //A and B are both square matrices and both have equal dimension
  34. //It multiplies A and B and stores into A
  35. void MatMult(Matrix& A, Matrix& B)
  36. {
  37.     int dim=A.len;
  38.     Matrix tmp(dim);
  39.    
  40.  
  41.     for(int i=0;i<dim;i++)    {
  42.         for(int j=0;j<dim;j++)    {
  43.             for(int k=0;k<dim;k++)    {
  44.                 tmp.mat[i][j]+=A.mat[i][k]*B.mat[k][j];
  45.                 tmp.mat[i][j]%=MOD;
  46.             }
  47.         }
  48.     }
  49.  
  50.     for(int i=0;i<dim;i++)    {
  51.         for(int j=0;j<dim;j++)    {
  52.             A.mat[i][j]=tmp.mat[i][j];
  53.         }
  54.     }
  55. }
  56.  
  57. //Calculates A^r and returns.
  58. Matrix MatExp(Matrix& A,ll r)
  59. {
  60.     int dim=A.len;
  61.     Matrix ret(dim);
  62.     ret.setToUnitMatrix();
  63.  
  64.     while(r)    {
  65.         if(r&1)    {
  66.             MatMult(ret,A);
  67.         }
  68.         MatMult(A,A);
  69.         r=r/2;
  70.     }
  71.  
  72.     return ret;
  73. }
  74.  
  75.  
  76.  
  77.  
  78. int main()
  79. {
  80.     //freopen("testcases.txt","r",stdin);
  81.  
  82.     Matrix Fib(2);
  83.     Fib.mat[0][0]=1;
  84.     Fib.mat[0][1]=1;
  85.     Fib.mat[1][0]=1;
  86.     Fib.mat[1][1]=0;
  87.  
  88.     ll n;
  89.     cin>>n;
  90.  
  91.     Matrix Fin= MatExp(Fib,n);
  92.  
  93.     cout<<Fin.mat[0][0]<<endl;
  94.    
  95.  
  96.  
  97.  
  98.     return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement