zoukankan      html  css  js  c++  java
  • 矩阵快速幂

    //矩阵快速幂,本题二阶矩阵
    #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 ",m);

    }

    题目链接

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

  • 相关阅读:
    Leetcode 1489找到最小生成树李关键边和伪关键边
    Leetcode 113 路径总和 II
    hdu 1223 还是畅通工程
    hdu 1087 Super Jumping! Jumping! Jumping!
    hdu 1008 Elevator
    hdu 1037 Keep on Truckin'
    湖工oj 1241 畅通工程
    湖工oj 1162 大武汉局域网
    hdu 2057 A + B Again
    poj 2236 Wireless Network
  • 原文地址:https://www.cnblogs.com/1998LJY/p/9328156.html
Copyright © 2011-2022 走看看