[poj 3318] Matrix Multiplication (随机化+矩阵)

时间:2021-09-02 16:24:27

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.

注意:只需要判断是否一样

如果A*B=C 那么 A*(B*R)=C*R

用一个随机数组(R)当做矩阵然后再乘即可变为O(n^2)

code:

//By Menteur_Hxy
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#define ll long long
#define f(a,b,c) for(int a=b;a<=c;a++)
using namespace std; inline ll rd() {
ll x=0,fla=1; char c=' ';
while(c>'9'|| c<'0') {if(c=='-') fla=-fla; c=getchar();}
while(c<='9' && c>='0') x=x*10+c-'0',c=getchar();
return x*fla;
} const int MAX=1010;
const int INF=0x3f3f3f3f;
int n;
int a[MAX][MAX],b[MAX][MAX],c[MAX][MAX],ans1[MAX],ans2[MAX],rnd[MAX]; void mul(int a[MAX],int b[MAX][MAX],int c[MAX]) {
int reg[MAX];
f(i,1,n) {
reg[i]=0;
f(j,1,n) reg[i]+=a[j]*b[j][i];
}
f(i,1,n) c[i]=reg[i];
} bool jud() {
f(i,1,n) if(ans1[i]!=ans2[i]) return 0;
return 1;
} int main() {
f(i,1,MAX) rnd[i]=rand();
while(scanf("%d",&n)==1) {
f(i,1,n) f(j,1,n) a[i][j]=rd();
f(i,1,n) f(j,1,n) b[i][j]=rd();
f(i,1,n) f(j,1,n) c[i][j]=rd();
mul(rnd,a,ans1);mul(ans1,b,ans1);mul(rnd,c,ans2);
if(jud()) printf("YES\n");
else printf("NO\n");
}
return 0;
}