矩阵快速幂

//矩阵快速幂,本题二阶矩阵
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;

const int mod = 1e9+7;
struct Matrix
{
  long long mat[2][2];
  Matrix()
  {
    memset(mat,0,sizeof(mat));
  }
  Matrix operator * (const Matrix &b)
  {
    Matrix res;
    for (int i=0; i<2; ++i)
    {
      for (int j=0; j<2; ++j)
      {
        for (int k=0; k<2; ++k)
        {
          res.mat[i][j]+=mat[i][k]*b.mat[k][j];
          res.mat[i][j]%=mod;
        }
      }
    }
    return res;
  }

};

Matrix operator ^ (Matrix a,long long n)
{
  Matrix res;
  for (int i=0; i<2; ++i)
    res.mat[i][i]=1;
  while(n)
  {
    if(n&1)
      res=res*a;
    a=a*a;
  n>>=1;
  }
  return res;
}
int main()
{
  long long n, m;
  Matrix a, s;

  //推导的矩阵内容
  a.mat[0][0] = 3;
  a.mat[0][1] = 1;
  a.mat[1][0] = 1;
  a.mat[1][1] = 3;

  scanf("%I64d", &n);
  if(n == 0)
  {
    puts("1");
    return 0;
  }
  s = a^(n-1);//矩阵快速幂的应用
  m = (s.mat[0][0]*3+s.mat[0][1]*1)%mod;//最后的结果式子
  printf("%I64d\n",m);

}

题目链接

http://120.78.128.11/Problem.jsp?pid=3347

posted @ 2018-07-18 11:19  窗子外和窗子里  阅读(89)  评论(0编辑  收藏  举报