您的位置:首页 > 其它

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

2016-07-29 11:53 507 查看
Matrix Multiplication

Time Limit: 2000MSMemory Limit: 65536K
Total Submissions: 17783Accepted: 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=250010;
struct Array{
int a[maxn],L;
int *operator[](int x){
return &a[(x-1)*L];
}
};
struct Matrix{
int R,C;
Array mat;
Matrix(){
memset(mat.a,0,sizeof(mat.a));
R=C=0;
}
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=1;i<=a.R;i++)
for(int j=1;j<=b.C;j++)
for(int k=1;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=1;i<=a.R;i++)
for(int j=1;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,1);
for(int i=1;i<=n;i++)
D[i][1]=rand();
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
scanf("%d",&x);
A[i][j]=x;
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
scanf("%d",&x);
B[i][j]=x;
}
}
for(int i=1;i<=n;i++){
for(int j=1;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 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: