[ACM] poj 3318 matrix multiplication (randomization algorithm)

Source: Internet
Author: User

Matrix Multiplication
Time limit:2000 ms   Memory limit:65536 K
Total submissions:16118   Accepted:3485

Description

You are given threeN×NMatricesA,BAndC. Does the equationA×B=CHold true?

Input

The first line of input contains a positive integerN(NLess than or equal to 500) followed by the three matricesA,BAndCRespectively. Each matrix's description is a block of n × n integers.

It guarantees that the elementsAAndBAre less than 100 in absolute value and elementsCAre less than 10,000,000 in absolute value.

Output

Output "yes" if the equation holds true, otherwise "no ".

Sample Input

21 02 35 10 85 110 26

Sample output

YES

Hint

Multiple inputs will be tested. So O (N3) algorithm will get TLE.

Source

Poj monthly -- 2007.08.05, qzc


Solution:

The question is given n * n matrices A, B, C. If a * B = C, the output is yes; otherwise, the output is no.

The first time we got into touch with the randomization algorithm, it was really amazing. Use a computer to randomly give the values that match the meaning of the question, and then calculate whether there is a conflict based on the relationship between the meaning of the question. If yes, it will fail. For example, a row and a column COL are randomly given in this question.

For (INT I = 1; I <= N; I ++)
Temp + = A [row] [I] * B [I] [col];Temp = C [row] [col];

If there is an inequality, it is definitely not a * B = C. However, the random number of times here is a problem. If the number of times is too large, it is too long to get the correct answer, so try to be a little more than all possible situations. This disadvantage will be solved in the second method below.

Baidu encyclopedia said very well:

The randomization algorithm uses a random function. The return value of a random function directly or indirectly affects the execution flow or result of the algorithm. The randomization algorithm is based on the random method and depends on the probability size.

In our lives, people often throw the dice to see the results and cast coins to decide the action. This involves a problem: Random.

This algorithm seems to work with luck. In fact, the randomization algorithm has a certain theoretical basis. We can imagine that in the closed interval [1, 1000], times at random, the probability of a random number of 2 is large (about 0.1), not to mention the chance of a random number of 1000 times in computer programs is just a blink of an eye. It can be seen that the randomization algorithm has broad prospects. However, since the randomization algorithm is difficult to control, not many people have been familiar with it, but many people have heard of it.

For example, we will solve the Randomization problem. For example, the length of a piece is 4 .. in the string of 10, you need to determine whether several characters can be deleted from the string so that the changed string meets one of the following conditions: (1) AAAA; (2) AABB; (3) Abab; (4) Abba. For example, if the length is 6 strings "popkdk" and two letters "O" and "d" are deleted, the original string is changed to "ppkk", which meets the condition (2) AABB. Analysis: This question is easy to come up with an algorithm: sort and combine: enumerate every four letters and then judge them one by one. The algorithm is feasible, but if you need to add a sentence to the question: You need to judge n strings, and n <= 100000, the time consumption is intolerable. Because it is a waste of time in the enumeration process. ( ①:The general algorithm time required in informatics is 1000 ms. PossibleWe can use the randomization algorithm to calculate the total number of methods for getting 4 characters from 10 characters: C (210) =. It is easy to know that if the randomization algorithm is random for 300 times, the expected result is basically correct (the probability is 1-(209/210) ^ 300, about 0.76 ), the random time consumption is O (1). You only need to judge that there is no random repetition. the time complexity of the determination is O (1), and the maximum random time is 300, in this way, we can effectively obtain the answer. The maximum number of operations is O (1000 N), which is within the computer's tolerable range (MS. From this we can see that the randomization algorithm is a good probability algorithm, but it cannot be guaranteed to be correct, and it is rarely used independently, most of which are similar to other algorithms: such as greedy and search. Example 2 Sorting Problem.Quick sorting is one of the most convenient sorting methods, but because it is extremely unstable, it is best to set the time complexity to O (N ㏒ N ), here, the base-2 logarithm is used. In the worst case, we can achieve the same O (N ^ 2) as normal sorting methods ). There are two restrictions on fast sorting: one is data, the more unordered data, the faster the speed of fast sorting; the other is enumeration of intermediate points. Because both constraints have an inseparable relationship with random. Therefore, it is important to add the randomization algorithm to the quick sorting. Used in: (1) random discharge of Data locations during data reading. (2) enumeration of intermediate points is determined after multiple randomization. In this way, the time complexity of quick sorting is basically maintained in the best state.

Method 1 code:

# Include <iostream> # include <time. h> # include <stdio. h> # include <stdlib. h> using namespace STD; const int maxn = 510; int A [maxn] [maxn]; int B [maxn] [maxn]; int C [maxn] [maxn]; int N; void input (int c [maxn] [maxn]) {for (INT I = 1; I <= N; I ++) for (Int J = 1; j <= N; j ++) scanf ("% d", & C [I] [J]);} bool OK () {int row, Col; // number of random rows, number of columns for (int K = 1; k <= 30000; k ++) {ROW = rand () % N + 1; Col = rand () % N + 1; int temp = 0; For (INT I = 1; I <= N; I ++) temp + = A [row] [I] * B [I] [col]; If (temp! = C [row] [col]) return false;} return true;} int main () {scanf ("% d", & N ); srand (Time (null); input (a); input (B); input (c); If (OK () cout <"yes" <Endl; else cout <"no" <Endl; return 0 ;}

Method 2:

If we multiply the vector R [] from the left by a row of n columns, there must beR * a * B = r * C

Code:

#include <iostream>#include <time.h>#include <stdio.h>#include <string.h>#include <stdlib.h>using namespace std;const int maxn=510;int A[maxn][maxn];int B[maxn][maxn];int C[maxn][maxn];int r[maxn];int rA[maxn];int rAB[maxn];int rC[maxn];int n;void input(int c[maxn][maxn]){    for(int i=1;i<=n;i++)        for(int j=1;j<=n;j++)        scanf("%d",&c[i][j]);}bool ok(){    for(int j=1;j<=n;j++)        for(int i=1;i<=n;i++)    {        rA[j]+=r[i]*A[i][j];        rC[j]+=r[i]*C[i][j];    }    for(int j=1;j<=n;j++)        for(int i=1;i<=n;i++)        rAB[j]+=rA[i]*B[i][j];    for(int i=1;i<=n;i++)        if(rAB[i]!=rC[i])        return false;    return true;}int main(){    scanf("%d",&n);    srand(time(NULL));    input(A);    input(B);    input(C);    memset(rA,0,sizeof(rA));    memset(rAB,0,sizeof(rAB));    memset(rC,0,sizeof(rC));    for(int i=1;i<=n;i++)        r[i]=rand()%99+1;    if(ok())        cout<<"YES"<<endl;    else        cout<<"NO"<<endl;    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.