Problem A. Matrix God(矩阵降维运算)
题意:判断三个矩阵是否满足C = A*B
Problem A. Matrix God
Input file: standard input
Output file: standard output
Time limit: 2 seconds
Memory limit: 256 megabytes
Matrices are square tables, containing integers in rows and columns. Do you know how to multiply
matrices? The product of matrices A and B of size n × n is a matrix C = AB, such that
C (i, j) = ∑n
k=1
A (i, k) · B (k, j).
Here the brackets contain numbers of row and column, where the corresponding element of matrix is
located.
As it is known, multiplying matrices is not the computationally simplest task. But not for Matrix god!
He can easily multiply matrices using the number of operations of order O
(
n
2
)
. Here and now for some
incomprehensible for mortals reason he is trying to determine, is it true that AB = C for three given
matrices A, B and C. For him solving this problem has no difficulties. Can you compare with him? The
Matrix god gives you an advantage: determine, at least, whether or not reminders of division of each
C (i, j) by 109 + 7 are found correctly.
Input
The first line contains a single integer n (1 ≤ n ≤ 1000) — the size of all matrices.
Then in n lines n integers aij , separated by a space, are given (0 ≤ ai,j ≤ 109 + 6) — the elements of
matrix A. In the next n lines the elements of matrix B are given in the same way, and after that in n
more lines — the reminders of division of elements of matrix C by 109 + 7.
Output
Output «YES» without quotes, if the reminders of division by 109 + 7 of each element of matrix C are
found correctly, otherwise output «NO» without quotes.
Page 1 of 2
,
Examples
standard input standard output
2
1 2
3 4
5 6
7 8
19 22
43 50
YES
3
1 2 3
4 5 6
7 8 9
1 4 7
2 5 8
3 6 9
14 32 50
32 76 122
50 122 194
NO
1
1000000006
1000000006
1
YES
思路:一开始想直接暴力的,但是三层循环的话就就1e9了,for循环会炸掉,然后就是想到了降维,利用一个一维的矩阵rad降低这三个矩阵的维度,判断rad * A * B=rad * C这个所用的时间就少了,就OK了。
代码如下:
#include<bits/stdc++.h>
using namespace std;
#define maxn 1005
#define mm 1000000007
int a[maxn][maxn], b[maxn][maxn], c[maxn][maxn];
long long rad[maxn], x[maxn], y[maxn], z[maxn];
int main()
{
ios::sync_with_stdio(0);
int n;
cin >> n;
for(int i = 0; i < n; i ++)
{
rad[i] = rand()%mm;
}
for(int i = 0; i < n; i ++)
for(int j = 0; j < n; j ++)
cin >> a[i][j];
for(int i = 0;i < n; i ++)
for(int j = 0; j < n; j ++)
cin >> b[i][j];
for(int i = 0; i < n; i ++)
for(int j = 0; j < n; j ++)
cin >> c[i][j];
int k = 0;
for(int j = 0; j <n; j ++)
{
int zz = 0;
for(int i = 0; i < n; i ++)
{
x[k] =(x[k]+rad[zz++]*a[i][j]%mm)%mm;
}
k++;
}
k = 0;
for(int j = 0; j <n; j ++)
{
int zz = 0;
for(int i = 0; i < n; i ++)
{
z[k] =(z[k]+rad[zz++]*c[i][j]%mm)%mm;
}
k++;
}
k = 0;
for(int j = 0; j <n; j ++)
{
int zz = 0;
for(int i = 0; i < n; i ++)
{
y[k] =(y[k]+x[zz++]*b[i][j]%mm)%mm;
}
k++;
}
int i;
int f =0;
for(i = 0; i < n; i ++)
{
if(y[i] != z[i])
{
f = 1;
break;
}
}
if(f) cout <<"NO"<<endl;
else cout <<"YES"<<endl;
return 0;
}