Poj 3318 Matrix Multiplication( 矩阵压缩)

时间:2022-02-27 16:23:32
Matrix Multiplication
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 18928   Accepted: 4074

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.

Source

 
/*
题意:有3个n*n的矩阵A,B,C,问AB是否等于C。
思路:题目描述很简单,就是用矩阵乘法,但是很明显矩阵乘法的时间复杂度为O(n^3),很明显超时。那怎么改进呢?就是用压缩矩阵的方法:
设矩阵R是1*n的矩阵,根据矩阵的性质,若R*A*B=R*C,那么A*B=C。由此可以看出来,虽然多成了一个矩阵,但是时间复杂度成了O(n^2)。那么问题是这个R的行列式该怎么设定,有人用的随机算法,但是随机算法可能在关键点上出现错误,可以将R设定成一个递增的数列{1,2,3……}。
*/
#include<iostream>
#include<vector>
#include<stdio.h>
#include<string.h>
using namespace std;
int n,x;
int a[][],b[][],c[][];
bool work()
{
int R[],ra[],rab[],rc[];
for(int i=;i<=n;i++) {R[i]=i; ra[i]=; rab[i]=; rc[i]=;} for(int j=;j<=n;j++)
for(int i=;i<=n;i++)
ra[j]+=R[i]*a[i][j]; for(int j=;j<=n;j++)
for(int i=;i<=n;i++)
rab[j]+=ra[i]*b[i][j]; for(int j=;j<=n;j++)
for(int i=;i<=n;i++)
rc[j]+=R[i]*c[i][j]; for(int i=;i<=n;i++)
if (rab[i]!=rc[i]) return ;
return ;
}
int main()
{
scanf("%d",&n);
for(int i=;i<=n;i++)
for(int j=;j<=n;j++)
scanf("%d",&a[i][j]);
for(int i=;i<=n;i++)
for(int j=;j<=n;j++)
scanf("%d",&b[i][j]);
for(int i=;i<=n;i++)
for(int j=;j<=n;j++)
scanf("%d",&c[i][j]);
if (work()) printf("YES\n");
else printf("NO\n");
return ;
}