矩阵快速幂

 1 #include
 2 #define ll long long 
 3 #define scan(i) scanf("%d",&i)
 4 #define scand(i) scanf("%lf",&i)
 5 #define scanl(i) scanf("%lld",&i)
 6 #define f(i,a,b) for(int i=a;i<=b;i++) 
 7 #define pb(i) push_back(i)
 8 #define ppb pop_back()
 9 #define pf printf
10 #define debug(i,j) i==j?cout<<"correct!\n":cout<<"wrong~\n"<11 using namespace std;
12 int t;
13 ll n; 
14 ll mi[5][5]={
15     2,4,1,0,0,
16     1,0,0,0,0,
17     0,0,1,2,1,
18     0,0,0,1,1,
19     0,0,0,0,1
20 };
21 const ll mod=998244353;
22 const int N=5;  
23 ll tmp[N][N]; 
24 ll qpow(ll x,ll i)//ans=x^i
25 {
26     ll ans = 1;
27     while(i)
28     {
29         if(i&1) ans = (ans*x)%mod;
30         i >>= 1;
31         x = (x*x)%mod;
32     }
33     return ans;
34 }
35 void multi(ll a[][N],ll b[][N],ll n)//a=axb 
36 {  
37     memset(tmp,0,sizeof tmp);  
38     for(ll i=0;i){
39         for(ll j=0;j){
40             for(ll k=0;k)  
41                 tmp[i][j]+=a[i][k]*b[k][j];
42                tmp[i][j]%=mod;
43         }
44     }
45     for(ll i=0;i){
46         for(ll j=0;j){
47             a[i][j]=tmp[i][j];
48         }
49     }
50 }  
51 ll res[N][N];  
52 void print(){
53     for(int i=0;i){
54         for(int j=0;j){
55             cout<" ";
56         }
57         cout<<endl;
58     }
59 } 
60 void Pow(ll n)//res=a^n
61 {  
62 
63     ll a[5][5]={
64     2,4,1,0,0,
65     1,0,0,0,0,
66     0,0,1,2,1,
67     0,0,0,1,1,
68     0,0,0,0,1
69     };
70     memset(res,0,sizeof(res));//n是幂,N是矩阵大小  
71     for(int i=0;i1;  
72     while(n){  
73         if(n&1) multi(res,a,N);//res=res*a;复制直接在multi里面实现了;  
74         multi(a,a,N);//a=a*a
75         n>>=1;  
76     }  
77 }  

N是矩阵大小,a是做幂运算的矩阵,n是幂次,mod是取的模

你可能感兴趣的:(矩阵快速幂)