【POJ 3318】Matrix Multiplication(随机……算法?)

Matrix Multiplication
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 17860 Accepted: 3857

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

Hint

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

Source

POJ Monthly–2007.08.05, qzc






……很无聊的题……
不过矩阵乘法 AB == C判断是 O(n3)
通过1*n的矩阵X XAB == C来判断,变成 O(3n3) ……还是。。。蛮。。。

毕竟做乘法结果是肯定保证无误的,不过毕竟这里用来判断矩阵相同……跟随机输出一个数跟服务器拼RP差不多了……或者。。有什么特殊的证明能保证这样判断几次无误,矩阵就一定相等?。。

观察大牛博客,有说用一个递增的1*n的矩阵,可以保证结果尽可能正确……

还有跑十次随机的做法……

或者输入优化,然后 O(n3) 判断……

无聊题

代码随便贴一下吧。。

#include 
#include 
#include 
#include 
#include 
#define LL long long

using namespace std;

int n;
LL mat[3][555][555];
LL ans[3][555];

int read()
{
    int d=0;
    char c,t=0;
    while((c=getchar())==' '||c=='\n');
    if(c=='-')
        t=1;
    else
        d=c-'0';
    while((c=getchar())>='0'&&c<='9')
        d=d*10+c-'0';
    if(t)
        return -d;
    else
        return d;
}

bool cal()
{
    memset(ans,0,sizeof(ans));

    for(int i = 0; i < n; ++i)
        for(int j = 0; j < n; ++j)
            ans[0][j] += mat[0][i][j]*(i+1);

    for(int i = 0; i < n; ++i)
        for(int j = 0; j < n; ++j)
            ans[1][j] += mat[1][i][j]*ans[0][i];

    for(int i = 0; i < n; ++i)
        for(int j = 0; j < n; ++j)
            ans[2][j] += mat[2][i][j]*(i+1);

    for(int i = 0; i < n; ++i)
        if(ans[2][i] != ans[1][i]) return false;

    return true;
}

int main()
{
    while(~scanf("%d",&n))
    {
        for(int k = 0; k < 3; ++k)
        for(int i = 0; i < n; ++i)
            for(int j = 0; j < n; ++j)
                mat[k][i][j] = read();

        puts(cal()? "YES": "NO");
    }
    return 0;
}

你可能感兴趣的:(POJ)