#include using namespace std; struct VectorHash { size_t operator()(const vector& v) const { size_t h = 0; for (int x : v) { h ^= hash{}(x) + 0x9e3779b9 + (h << 6) + (h >> 2); } return h; } }; int brute(int N, const vector>& A) { int M = A.size(); vector S(M), G(M); for (int i = 0; i < M; ++i) { S[i] = A[i].first; G[i] = A[i].second; } queue> que; unordered_map, int, VectorHash> dist; dist[S] = 0; que.push(S); while (!que.empty()) { auto X = que.front(); que.pop(); int d = dist[X]; if (X == G) { return d; } for (int F = 1; F <= N; ++F) { int mn = N + 1; // F に最も近い距離を求める for (int i = 0; i < M; ++i) { mn = min(mn, abs(X[i] - F)); } // 同率最小のエレベーターはすべて選択候補 for (int i = 0; i < M; ++i) { if (abs(X[i] - F) != mn) continue; // 動かない遷移は不要 if (X[i] == F) continue; auto Y = X; Y[i] = F; if (!dist.count(Y)) { dist[Y] = d + 1; que.push(Y); } } } } return -1; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; while (Q--) { int N, M; cin >> N >> M; vector> A(M); for (auto& [s, g] : A) cin >> s; for (auto& [s, g] : A) cin >> g; // ラベルを付け替えているだけなので、 // (S_i, G_i) ごとソートしても問題ない sort(A.begin(), A.end()); cout << brute(N, A) << '\n'; } }