POJ3318--Matrix Multiplication 随机化算法

Description

You are given three n × n matrices A, B and C. Does the equation A × B = C hold true?

Input

The first line of input contains a positive integer n (n ≤ 500) followed by the the three matrices A, B and C respectively. Each matrix's description is a block of n × n integers.

It guarantees that the elements of A and B are less than 100 in absolute value and elements of C are less than 10,000,000 in absolute value.

Output

Output "YES" if the equation holds true, otherwise "NO".

Sample Input

2
1 0
2 3
5 1
0 8
5 1
10 26

Sample Output

YES

这个题目太甩了, 完全用随机的方法在有限次尝试以后,判断是否正确, 美其名曰 “随机化算法”。 实际就是取随机数,每次只计算矩阵C中一个位置上的值,如果通过A、B 计算出来的结果与C相同,进入下一次循环,不同就跳出,同时输出NO。 有限次循环后,如果都正确,输出YES。
但是这里面随机数的种子选取是根据当前时间来计算的,也就意味着结果是否正确跟测试用例、尝试次数和当前时间都有关系。同样的代码不同时间提交,可能结果不同。 还有个地方要注意,scanf真的比cin快好多,如果用cin根本没办法尝试太多次,得到的结果肯定错误。
关于scanf和cin的速度测试这有一篇博文写的比较详细 http://blog.sina.com.cn/s/blog_93294724010163rl.html

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime> 

using namespace std;

int n;

int matrixA[501][501];
int matrixB[501][501];
int matrixC[501][501];

int main()
{
    scanf("%d", &n);

        for(int j=1; j<=n; ++j)
        {
            for(int k=1; k<=n; ++k)
            {
                scanf("%d", &matrixA[j][k]);
            }
        }
        for(int j=1; j<=n; ++j)
        {
            for(int k=1; k<=n; ++k)
            {
                scanf("%d", &matrixB[j][k]);
            }
        }
        for(int j=1; j<=n; ++j)
        {
            for(int k=1; k<=n; ++k)
            {
                scanf("%d", &matrixC[j][k]);
            }
        }
    bool flag = true;

    srand((unsigned)time(NULL));  
    for(int i=0; i<80000; i++)
    {
        int r = rand()%n+1;
        int c = rand()%n+1;
        int sum = 0;
        for(int j=1; j<=n; ++j)
        {
            sum += matrixA[r][j]*matrixB[j][c];
        }

        if(sum != matrixC[r][c])
        {
            flag = false;
            break;
        }
    }

    if(flag)
        cout << "YES" << endl;
    else
        cout << "NO" << endl;


}


原文地址:https://www.cnblogs.com/scarecrow-blog/p/4503777.html