Original Intention: N blocks are arranged in a column, each of which can be marked as red, blue, green, or yellow. Ask the number of solutions where both the red and green squares are even numbers.
SOL: Finding regular column recursion + rapid matrix power
Set the number of I + 1 blocks that have been dyed.
In a [I] = 1-I blocks, the number of red and green blocks is an even number of solutions.
In B [I] = 1-I blocks, the number of red and green blocks is an even number and the number of solutions is an odd number (Red even green odd or red odd Green even)
C [I] = in 1-I blocks, the number of red and green blocks is an odd number of solutions.
The recursive formula can be obtained:
A [I + 1] = 2 * A [I] + B [I]
B [I + 1] = 2 * A [I] + 2 * B [I] + 2 * C [I]
C [I + 1] = B [I] + 2 * C [I]
How to combine with a matrix? Write the formula like this,
A [I + 1] = 2 * A [I] + 1 * B [I] + 0 * C [I]
B [I + 1] = 2 * A [I] + 2 * B [I] + 2 * C [I]
C [I + 1] = 0 * A [I] + 1 * B [I] + 2 * C [I]
Then, YY generates a matrix:
Therefore,
In this way, you can use the Matrix to quickly calculate the power.
1 #include "iostream" 2 #include "vector" 3 #include "cstring" 4 using namespace std; 5 6 typedef unsigned long int ULL; 7 typedef vector<ULL> vec; 8 typedef vector<vec> mat; 9 const ULL P=10007;10 int n,m;11 12 mat mul(mat &A,mat &B) //return A*B13 {14 mat C(A.size(),vec(B[0].size()));15 for (int i=0;i<(int)A.size();i++)16 {17 for (int k=0;k<(int)B.size();k++)18 {19 for (int j=0;j<(int)B[0].size();j++)20 {21 C[i][j]=(C[i][j]+A[i][k]*B[k][j])%P;22 }23 }24 }25 return C;26 }27 28 mat m_pow(mat A,int m) //return A^m29 {30 mat B(A.size(),vec(A.size()));31 for (int i=0;i<(int)A.size();i++)32 B[i][i]=1;33 while (m>0)34 {35 if (m&1) B=mul(B,A);36 A=mul(A,A);37 m>>=1;38 }39 return B;40 }41 42 int main()43 {44 int T,N;45 cin>>T;46 while (T--)47 {48 cin>>N;49 mat A(3,vec(3));50 A[0][0]=2; A[0][1]=1; A[0][2]=0;51 A[1][0]=2; A[1][1]=2; A[1][2]=2;52 A[2][0]=0; A[2][1]=1; A[2][2]=2;53 54 A=m_pow(A,N);55 56 cout<<A[0][0]<<endl;57 }58 return 0;59 }60 61 /*62 int main()63 {64 int T;65 cin>>T;66 while (T--)67 {68 cin>>n>>m;69 mat A(n,vec(n));70 71 for (int i=0;i<n;i++)72 for (int j=0;j<n;j++)73 cin>>A[i][j];74 75 A=m_pow(A,m);76 77 ULL ans=0;78 for (int i=0;i<n;i++)79 {80 ans+=A[i][i];81 ans=ans%P;82 }83 cout<<ans<<endl;84 }85 return 0;86 }87 */
View code
Poj 3734 rapid matrix power + YY