数学(矩阵乘法,随机化算法):POJ 3318 Matrix Multiplication

时间:2022-02-13 10:50:30
Matrix Multiplication
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 17783   Accepted: 3845

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(n3) algorithm will get TLE.
  用个一维随机矩阵去乘再判断是否相等,类似与哈希的思想。
 #include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
const int maxn=;
struct Array{
int a[maxn],L;
int *operator[](int x){
return &a[(x-)*L];
}
};
struct Matrix{
int R,C;
Array mat;
Matrix(){
memset(mat.a,,sizeof(mat.a));
R=C=;
}
void Init(int r,int c){
R=r;mat.L=C=c;
}
int *operator[](int x){
return mat[x];
}
friend Matrix operator*(Matrix a,Matrix b){
Matrix c;c.Init(a.R,b.C);
for(int i=;i<=a.R;i++)
for(int j=;j<=b.C;j++)
for(int k=;k<=a.C;k++)
c[i][j]+=a[i][k]*b[k][j];
return c;
}
friend bool operator ==(Matrix a,Matrix b){
if(a.R!=b.R||a.C!=b.C)return false;
for(int i=;i<=a.R;i++)
for(int j=;j<=b.C;j++)
if(a[i][j]!=b[i][j])
return false;
return true;
}
}A,B,C,D;
int main(){
int n,x;
scanf("%d",&n);srand(n);
A.Init(n,n);
B.Init(n,n);
C.Init(n,n);
D.Init(n,);
for(int i=;i<=n;i++)
D[i][]=rand();
for(int i=;i<=n;i++){
for(int j=;j<=n;j++){
scanf("%d",&x);
A[i][j]=x;
}
}
for(int i=;i<=n;i++){
for(int j=;j<=n;j++){
scanf("%d",&x);
B[i][j]=x;
}
}
for(int i=;i<=n;i++){
for(int j=;j<=n;j++){
scanf("%d",&x);
C[i][j]=x;
}
}
A=A*(B*D);
C=C*D;
if(A==C)
printf("YES\n");
else
printf("NO\n");
return ;
}