Ten typical problems solved by matrix multiplication (maxtrix67 ))

Source: Internet
Author: User

 

It seems that there is no summary of this topic. I have seen four people who have asked such questions in a row over the past few days. I will briefly write them here today. Here we will not introduce other matrix-related knowledge, but will only introduce matrix multiplication and related properties.
Do not think that the matrix in mathematics is also a changing green character on the black screen. In mathematics, a matrix is a two-dimensional array. A matrix of N rows and M columns can be multiplied by a matrix of m rows and P columns. The result is a matrix of N rows and P columns, the number at the position of column J in row I is equal to the number of M in row I in the previous matrix and the number of M in column J in the next matrix are multiplied by all M products. and. For example, the following formula represents a matrix of two rows and two columns multiplied by a matrix of two rows and three columns. The result is a matrix of two rows and three columns. The 4 in the result is 2*2 + 0*1:

The formula below is a matrix of 1x3 multiplied by 3x2, and a matrix of 1X2 is obtained:

Two important properties of matrix multiplication: 1. Matrix MultiplicationNot satisfiedExchange law; 2. Matrix Multiplication satisfies the combination law. Why does matrix multiplication not meet the exchange law? The two matrices cannot be multiplied. Why does it satisfy the combination law? Think about it and you will find it is also nonsense. Assume that you have three matrices A, B, and C. Then, the numbers in column J of row I of the results of (AB) C and A (BC) are equal to all a (ik) * sum of B (kL) * C (LJ) (enumerate all K and L ).

Classic Question 1 is given n vertices and M operations to construct O (m + n)AlgorithmOutput the position of each point after M operations. Operations include translation, scaling, flip, and rotation.
The operation is performed on all vertices at the same time. Here, the rotation is based on the coordinate axis as the symmetric axis (in either case), and the rotation is centered on the origin. If we simulate each vertex separately, M operations consume O (Mn) in total ). Using Matrix Multiplication, all operations can be combined into a matrix in O (m) time, and then each vertex can be multiplied by the matrix to directly obtain the final position of the vertex, total time consumed O (m + n ). Assume that the coordinates of a certain point are X and Y at the beginning. The following five matrices can be translated, rotated, flipped, and rotated respectively. In advance, all the matrices corresponding to all M operations are multiplied by (X, Y, 1) to get the final point position.

If matrix A is given in classical question 2, calculate the result of a ^ n (n a) quickly, and output each number is mod p.
Because matrix multiplication has a combination law, a ^ 4 = A * a * A = (A * A) * (A * A) = a ^ 2 * a ^ 2. We can conclude that when n is an even number, a ^ n = a ^ (n/2) * A ^ (n/2); when n is an odd number, A ^ n = a ^ (n/2) * A ^ (n/2) * a (where n/2 is rounded up ). This tells us that the method for calculating a ^ n can also be used to quickly calculate the power of binary. For example, to calculate the value of a ^ 25, we only need to recursively calculate the values of a ^ 12, a ^ 6, and a ^ 3. Based on some of the results here, we can constantly modulo the computing process to avoid high-precision operations.

Typical Topic 3 poj3233(Thanks rmq)
Given matrix A, evaluate the result of A + A ^ 2 + A ^ 3 +... + A ^ K (the addition of the two matrices is the addition of the corresponding positions ). Output Data mod m. K <= 10 ^ 9.
This question is equivalent to a classic question. First, we know that a ^ I can be obtained in two parts. Then we need to divide the data size k of the entire question. For example, when K is 6, there are:
A + A ^ 2 + A ^ 3 + A ^ 4 + A ^ 5 + A ^ 6 =(A + A ^ 2 + A ^ 3)+ A ^ 3 *(A + A ^ 2 + A ^ 3)
After this formula is applied, the size of K is halved. After finding a ^ 3 in binary mode, recursively calculate a + A ^ 2 + A ^ 3 to obtain the answer to the original question.

Classic Topic 4 voj1049
Question: m replicas are given sequentially, and the M replicas are repeatedly used to operate the initial sequence. Ask the sequence after K replicas. M <= 10, k <2 ^ 31.
First, merge the M replicas (calculate the product of the M replicas), and then we need to execute the replicas K/M (take the integer, if there is an remainder, you can simulate it in a few steps ). Note that any replacement can be expressed as a matrix. For example, replacing 1 2 3 4 with 3 1 2 4 is equivalent to the following matrix multiplication:

Replacing K/M is equivalent to multiplying the k/M matrix. We can calculate the k/M power of the matrix in binary mode and multiply it by the initial sequence. Don't be too busy to be happy. The time of your satisfaction is the day of your destruction. Don't forget that there may be several replacements that need to be simulated in the end.

Typical Topic 5: algorithm art and informatics competition page 1 (207) (algebra methods and models, [Example 5] bacteria, different versions may have page deviations)
Let's take a look at it. The book is very detailed. Similar to the previous question, the solution uses a matrix to represent the operation, and then returns the final state in two parts.

In typical example 6, given N and P, calculate the value of mod P in the nth Number of ononacci. N cannot exceed 2 ^ 31.
Based on the previous ideas, we need to construct a 2x2 matrix so that it is multiplied by (A, B) and the result is (B, A + B ). Each time we multiply this matrix, the two numbers will be iterated once more. Then, we multiply the matrix of 2x2 by N times and then multiply it by () to obtain the number of the N ononacci. You don't have to think about it. This 2x2 matrix can be easily constructed:

Classic Topic 7 voj1067
We can use the above method to obtain the nth item of any linear recursive formula. The corresponding matrix construction method is: (n-1) * (n-1) in the upper right corner) fill in 1 on the primary diagonal line in the small matrix, fill in the corresponding coefficient in the nth line of the matrix, and fill in 0 in other places. For example, we can use the following matrix multiplication to calculate the K entry of F (n) = 4f (n-1)-3f (n-2) + 2f (n-4:

I can compile a truck of linear recursive relationships by using matrix multiplication. The example here is the case where all coefficients are 1.

In classic question 8, a directed graph is given, and the number of mod P values from point A to exactly K (allow repeated edge) to point B
Convert the given graph into an adjacent matrix, that is, if a (I, j) = 1 and only one edge I-> J exists. So that c = A * a, then C (I, j) = Σ a (I, k) * a (K, J ), in fact, it is equal to the number of paths from point I to Point J passing through two sides (enumeration K is a vertex ). Similarly, column J of row I of C * A indicates the number of paths passing through three edges from I to J. Similarly, if the number of paths passing through K Steps is required, we only need to obtain a ^ K in two parts.

Classic Question 9: How many schemes are there to fill m x n rectangles with 1X2 dominoes? m <= 5, n <2 ^ 31, output the result of mod p

Let's take M = 3 as an example. Suppose we place the rectangle horizontally on the computer screen and fill it in a column from right to left. Where the first N-2 column is filled, column N-1 is uneven. Now we need to fill up column N-1 and move the status to column N. Because the statuses of column N-1 are different (there are eight different statuses), we need to discuss them based on different situations. In the figure, I put the first eight different states on the left and the last eight different states on the right, A certain state on the Left can be transferred to a certain state on the right to connect a line between them. Note: to ensure that the scheme is not repeated, a domino card cannot be placed vertically in column n-1 During Status transition (for example, the 2nd states on the Left cannot be transferred to the 4th states on the right ), otherwise, this will be the same as the status before another transfer. Draw the transition relationships of these eight states into a directed graph. Then the problem becomes like this: Starting from status 111, how many solutions are there to return to this state after N steps. For example, there are three solutions for n = 2: 111-> 011-> 111, 111-> 110-> 111 and 111-> 000-> 111, this is one-to-one correspondence with the scheme of covering 3x2 rectangles with dominoes. In this way, this question is transformed into the previous example 8.
I wrote the source code for this question later. You can see the applications related to bit operations again.

Classic question 10 poj2778
The question is, how many possible N-bit DNA strings do not contain specified virus fragments. Valid DNA can only contain four characters: actg. The question will be given a virus segment of less than 10, each segment length cannot exceed 10. Data scale n <= 2 000 000 000.
In the following illustration, we take the four virus fragments: ATC, AAA, GGC, and CT as an example to illustrate how to convert the problem into Example 8 through the diagram above. We can find out the prefixes of all virus fragments and divide the n-bit DNA into the following seven types: end with at, end with AA, end with GG, end? A ends? G ends? C ends ?? End. The question mark indicates "Other Situations", which can be any letter, as long as the letter does not make its string a virus prefix. Obviously, these categories are a division of the complete set (the intersection is empty, and the set is the complete set ). Now, if we know the number of qualified DNA in all kinds of DNA with a length of N-1, we need to find the number of various types of DNA with a length of N. We can construct an edge weighted directed graph based on the transition between different types. For example, from at cannot be transferred to AA, from at ?? There are four methods (followed by a letter), from? There is one solution for a to transfer to AA (add a later), from? A transfer ?? There are two solutions (G or C is added later), from Gg ?? There are two solutions (adding C to the end will constitute a virus segment, which is invalid. Only a and t can be added. The construction process of this graph is similar to using finite state automation for string matching. Then, we will convert the graph into a matrix, so that the matrix can be multiplied by N times. The final output is from ?? The total number of paths from the status to all other statuses.
The data scale in the question ensures that the number of prefixes cannot exceed 100. One matrix multiplication is performed by three Parties, and a total of log (n) times are used. Therefore, the overall complexity of this question is 100 ^ 3 * log (N), AC.

Finally, I will give the 9th questionCodeFor your reference (I wrote today, and I am familiar with C ++ classes and operator overloading ). In order to prevent everyone from looking at the code and forgetting to look at it, I put this sentence above for example:
Matrix67 original, please indicate the source of the post.

# Include <cstdio> # Define Size (1 <m) # Define Max_size 32 Using   Namespace  STD;  Class  Cmatrix {  Public  :  Long  Element [max_size] [max_size];  Void Setsize ( Int  ); Void Setmodulo ( Int  ); Cmatrix  Operator * (Cmatrix); cmatrix power (  Int  );  Private  :  Int  Size;  Long  Modulo ;};  Void Cmatrix: setsize ( Int A ){  For ( Int I = 0 ; I <A; I ++ )  For ( Int J = 0 ; J <A; j ++ ) Element [I] [J] = 0  ; Size = A ;}  Void Cmatrix: setmodulo ( Int A) {modulo = A;} cmatrix ::  Operator * (Cmatrix PARAM) {cmatrix product; product. setsize (size); product. setmodulo (Modulo );  For ( Int I = 0 ; I <size; I ++ )  For ( Int J = 0 ; J <size; j ++ ) For ( Int K = 0 ; K <size; k ++ ) {Product. Element [I] [J] + = Element [I] [k] * Param. Element [k] [J]; product. Element [I] [J] % = Modulo ;}  Return  Product;} cmatrix: Power (  Int  Exp) {cmatrix TMP = (* This )*(* This );  If (Exp = 1 ) Return * This  ;  Else   If (Exp & 1 ) Return TMP. Power (exp/ 2 )*(* This  );  Else   Return TMP. Power (exp/ 2  );}  Int  Main (){  Const   Int Validset [] = { 0 , 3 , 6 , 12 , 15 , 24 , 27 , 30  }; Long  N, m, p; cmatrix unit; scanf (  "  % D  " , & N, & M ,& P); Unit. setsize (size );  For ( Int I = 0 ; I <size; I ++ )  For ( Int J = 0 ; J <size; j ++ ) If (((~ I) & J) = ((~ I) & (size- 1  ))){  Bool Isvalid = False  ;  For ( Int K = 0 ; K < 8 ; K ++) isvalid = isvalid | (I & J) = Validset [k]; Unit. Element [I] [J] = Isvalid;} unit. setmodulo (p); printf ( "  % D  " , Unit. Power (N). Element [size- 1 ] [Size- 1  ]);  Return   0  ;} 

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.