Matrix Multiplication
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.
思路:
正常来说肯定会想到直接按照题目的判断,但是矩阵乘法是O(n3)的,会超时。
引入一个行矩阵t,如果ab=c,则tab=tc,因为t只有一行,所以计算是O(n2)的,
为了保证正确性需要随机构造矩阵t,并且多测试几组。
code:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxm=505;
int a[maxm][maxm];
int b[maxm][maxm];
int c[maxm][maxm];
int a1[maxm];
int a2[maxm];
int a3[maxm];
int t[maxm];
int n;
bool check(){
for(int i=1;i<=n;i++){//t[]为随机造的行矩阵
t[i]=rand()%100;
}
for(int i=1;i<=n;i++){//清空存答案的数组
a1[i]=a2[i]=a3[i]=0;
}
for(int i=1;i<=n;i++){//t*a
for(int j=1;j<=n;j++){
a1[i]+=t[j]*a[j][i];
}
}
for(int i=1;i<=n;i++){//t*a的结果*b
for(int j=1;j<=n;j++){
a2[i]+=a1[j]*b[j][i];
}
}
for(int i=1;i<=n;i++){//t*c
for(int j=1;j<=n;j++){
a3[i]+=t[j]*c[j][i];
}
}
for(int i=1;i<=n;i++){//判断是否相同
if(a2[i]!=a3[i])return 0;
}
return 1;
}
signed main(){
while(scanf("%d",&n)!=EOF){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
scanf("%d",&a[i][j]);
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
scanf("%d",&b[i][j]);
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
scanf("%d",&c[i][j]);
}
}
int test=10;//测试10组
int ok=1;
while(test--){
if(!check()){
ok=0;
break;
}
}
puts(ok?"YES":"NO");
}
return 0;
}