矩阵快速幂2 3*n铺方格

 1 #include <iostream>
 2 #include <cstdlib>
 3 #include <cstring>
 4 #include <queue>
 5 #include <cstdio>
 6 #include <algorithm>
 7 #include <map>
 8 #include <time.h>
 9 #include <ext/pb_ds/assoc_container.hpp>
10 #include <ext/pb_ds/tree_policy.hpp>
11 #define LL long long
12 
13 using namespace std;
14 using namespace __gnu_pbds;
15 
16 //U[n]表示3×N棋盘的摆放数,
17 //
18 //V[n]表示缺了1×1边角的3×N棋盘的摆放数
19 //
20 //21 //
22 //U[n] = 2*V[n-1] + U[n-2]
23 //
24 //V[n] = U[n-1] + V[n-2]
25 //
26 //其中,
27 //
28 //U[0] = 1, U[2] = 3;
29 //
30 //V[0] = 1, V[1] =1;
31 
32 //[U(n)                       [ 0 2 1 0           [ U(n-1)
33 // V(n)                         1 0 0 1             V(n-1)
34 // U(n-1)        =              1 0 0 0      *      U(n-2)
35 // V(n-1)]                      0 1 0 0 ]           V(n-2) ]
36 //
37 //                   [ 0 2 1 0                    [ U(1)
38 //               =     1 0 0 1                      V(1)
39 //                     1 0 0 0     ^  (n-1)         U(0)
40 //                     0 1 0 0 ]                    V(0) ]
41 
42 const int MOD = 12357;
43 
44 struct Martix
45 {
46     LL martix[5][5];
47     int row,col;
48     Martix(int _row,int _col)
49     {
50         memset(martix,0,sizeof(martix));
51         row = _row;
52         col = _col;
53     }
54     Martix operator *(const Martix &A)const
55     {
56         Martix C(row, A.col);
57         for(int i = 0; i < row; i++)
58             for(int j = 0; j < A.col; j++)
59                 for(int k = 0; k < col; k++)
60                     C.martix[i][j] =  (C.martix[i][j] + martix[i][k] * A.martix[k][j])%MOD;
61         return C;
62     }
63 };
64 
65 
66 void solve()
67 {
68     Martix A(4,4), F(4,4), S(4,1);
69     A.martix[0][2] = A.martix[1][0] = A.martix[1][3] = A.martix[2][0] = A.martix[3][1] = 1;
70     F.martix[0][0] = F.martix[1][1] = F.martix[2][2] = F.martix[3][3] = 1;
71     A.martix[0][1] = 2;
72     S.martix[1][0] = S.martix[2][0] = S.martix[3][0] = 1;
73     int n;
74     scanf("%d",&n);
75     if(n&1)
76     {
77         printf("%d
",0);
78         return ;
79     }
80     n--;
81     while(n > 0)
82     {
83         if(n & 1)
84             F = F*A;
85         A = A*A;
86         n >>= 1;
87     }
88     S = F*S;
89     printf("%lld
",S.martix[0][0]);
90 }
91 
92 int main(void)
93 {
94     solve();
95     return 0;
96 }
原文地址:https://www.cnblogs.com/henserlinda/p/5741718.html