[概率]Matrix Multiplication
题目描述
You are given three n × n matrices A, B and C. Does the equation A × B = C hold true?
输入
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 "YES" if the equation holds true, otherwise "NO".
样例输入
2
1 0
2 3
5 1
0 8
5 1
10 26
样例输出
YES
提示
Multiple inputs will be tested. So algorithm will get TLE.
思路分析
直接计算矩阵乘积A×B并与C比较对于大矩阵来说计算量太大,不可行。
利用矩阵乘法的结合律,通过随机向量v来验证A×(B×v)是否等于C×v。如果A×B不等于C,那么对于随机向量v,结果很可能不匹配。
生成随机向量v,计算B×v和A×(B×v),再计算C×v,比较结果。重复多次以降低错误概率。
代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n;
int main() {ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);cin>>n;vector<vector<ll>>a(n+1,vector<ll>(n+1));vector<vector<ll>>b(n+1,vector<ll>(n+1));vector<vector<ll>>c(n+1,vector<ll>(n+1));for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){cin>>a[i][j];}}for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){cin>>b[i][j];}}for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){cin>>c[i][j];}}for(int test=1;test<=3;test++){vector<ll>x(n+1,0);vector<ll>v1(n+1,0);vector<ll>v2(n+1,0);vector<ll>v3(n+1,0);for(int i=1;i<=n;i++){x[i]+=rand()%2;}for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){v1[i]+=b[i][j]*x[j];}}for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){v2[i]+=a[i][j]*v1[j];}}for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){v3[i]+=c[i][j]*x[j];}}bool equ=true;for(int i=1;i<=n;i++){if(v2[i]!=v3[i]){equ=false;break;}}if(!equ){cout<<"NO";return 0;}}cout<<"YES";return 0;
}