Description
Gu Tianle is come back! And he take Zhen Zidan to go to Greedy Blue Moon! Here they comes a challenge, please help them!
They have two matrix A and B. The challenge is that they need to transform A to B. The only operation they can do is transpose any sub square matrices within the matrix A infinite times. Sub square matrices is any sub matrix within a matrix (may including itself), and the number of rows and columns of it are equal.
Can you tell Gu Tianle and Zhen Zidan if thay can complete the challenge?
Input
The first line contains two integers n and m separated by space (1≤n, m≤500) — the numbers of rows and columns in A and B respectively.
Each of the next n lines contains m integers, the j-th number in the i-th of these lines denotes the j-th element of the i-th row of the matrix A (1≤Aij≤10^9).
Each of the next n lines contains m integers, the j-th number in the i-th of these lines denotes the j-th element of the i-th row of the matrix B (1≤Bij≤10^9).
Output
Print “YES” if it is possible to transform A to B and “NO” otherwise.
Sample Input
2 2
4 4
4 5
5 4
4 4
3 3
1 2 3
4 5 6
7 8 9
1 4 7
2 5 6
3 8 9
Sample Output
NO
YES
题目大意
给定矩阵A和B,询问A矩阵能否通过以下操作变换为B矩阵。
·选择A矩阵的任意一个子矩阵并将其转置。
题解
若每次选择一个2*2子矩阵进行转置,可以让这个子矩阵的辅对角线元素交换,这个过程与交换排序相类似。进而考虑,矩阵A中所有平行于辅对角线的元素,都可以通过选择相邻元素并两两交换的过程实现排序。那么,若矩阵A可以转换成矩阵B,只需要对A和B平行于辅对角线所有斜线排个序。若两矩阵排序后的相同,说明可以转换。当然也可以不排序,使用hash判断。
代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
using namespace std;
inline int read() {
int s = 0, w = 1;
char ch = getchar();
while (ch < '0' || ch>'9') {
if (ch == '-')w = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
s = s * 10 + ch - '0';
ch = getchar();
}
return s * w;
}
int mat_a[505][505];
int mat_b[505][505];
int main()
{
int n, m;
while (cin >> n >> m) {
vector<vector<unsigned long long> >line_a(1010);
vector<vector<unsigned long long> >line_b(1010);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
mat_a[i][j] = read();
line_a[i + j].push_back(mat_a[i][j]);
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
mat_b[i][j] = read();
line_b[i + j].push_back(mat_b[i][j]);
}
}
bool ok = 1;
for (int i = 0; i < m + n - 1; ++i) {
int ll = line_a[i].size();
int ha = 0, hb = 0;
for (int j = 0; j < ll;++j) {
ha ^= line_a[i][j] * 100000007;
}
for (int j = 0; j < ll; ++j) {
hb ^= line_b[i][j] * 100000007;
}
if (ha!=hb) {
ok = 0;
break;
}
}
if (ok) {
puts("YES");
}
else {
puts("NO");
}
}
}