【模板】矩阵快速幂

 矩阵乘法不满足交换律 注意乘号前后的矩阵的顺序

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=100000+5;const long long mod=1e9+7;
long long n;
struct hehe{long long c[2][2];
            void init_0() {c[0][0]=c[0][1]=c[1][0]=c[1][1]=0;}
            void init_1() {c[0][0]=c[1][1]=1; c[1][0]=c[0][1]=0;}
            hehe operator * (const hehe &q) const
	         {hehe re; re.init_0();
			  for(int i=0;i<=1;i++)
	            for(int j=0;j<=1;j++)
	             for(int k=0;k<=1;k++)
	              re.c[i][j]=(re.c[i][j]+c[i][k]*q.c[k][j]%mod)%mod;

	          return re;
	         }
	         /*
	        friend hehe operator *(hehe a,hehe b)
            {
             hehe re; re.init_0();
             for(int i=0;i<=1;i++)
              for(int j=0;j<=1;j++)
                for(int k=0;k<=1;k++)
                    (re.c[i][j]+=1ll*a.c[i][k]*b.c[k][j]%mod)%=mod;
             return re;
            }*/
	        hehe operator + (hehe q) const
	         {hehe re; re.init_0();
			  for(int i=0;i<=1;i++)
	           for(int j=0;j<=1;j++)
	               re.c[i][j]=(c[i][j]+q.c[i][j])%mod;

	          return re;
	         }
           }tur,xiugai;

inline hehe ksm(hehe p,long long k)
 {hehe re; re.init_1();
  while(k)
 	{if(k&1) {re=p*re;}
 	 p=p*p;
 	 k>>=1;
 	}
  return re;
 }
int main()
{tur.c[0][0]=0; tur.c[0][1]=tur.c[1][0]=tur.c[1][1]=1;

  scanf("%lld",&n);

 hehe re; re.init_0(); re.c[0][0]=re.c[1][0]=1;

 //re=ksm(tur,n)*re;

 for(int k=1;k<=n;k++)
 {re.init_0(); re.c[0][0]=re.c[1][0]=1;
  re=ksm(tur,k)*re;
  for(int i=0;i<=1;i++)
  {for(int j=0;j<=1;j++)
     {printf("%lld ",re.c[i][j]);

     }
   printf("\n");
  }
  printf("\n\n");
 }
 printf("%lld\n",re.c[0][0]);
return 0;
}

 

posted @ 2018-11-08 21:00  YuXiaoze  阅读(101)  评论(0编辑  收藏  举报