ac
2026-03-22 17:31:02
发布于:浙江
#include <bits/stdc++.h>
using namespace std;
int count(vector<int> &a) {
int n = a.size(), res = 0;
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
if (a[i] > a[j]) ++res;
return res;
}
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int _; cin >> ;
while (--) {
int n, m;
cin >> n >> m;
vector<vector<int>> a(n, vector<int>(m));
vector<vector<int>> b(n, vector<int>(m));
for (auto &row : a)
for (auto &x : row) cin >> x;
for (auto &row : b)
for (auto &x : row) cin >> x;
vector<int> row(n), col(m);
iota(begin(row), end(row), 0);
iota(begin(col), end(col), 0);
int res = 100;
do {
do {
vector<vector<int>> c(n, vector<int>(m));
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
c[i][j] = a[row[i]][col[j]];
if (c != b) continue;
res = min(res, count(row) + count(col));
} while (next_permutation(begin(col), end(col)));
} while (next_permutation(begin(row), end(row)));
cout << (res < 100 ? res : -1) << '\n';
}
return 0;
}
这里空空如也






有帮助,赞一个