#include using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); const long long MAX_STATES = 2'000'000; int Q; cin >> Q; while (Q--) { int N, M; cin >> N >> M; vector S(M), G(M); for (int& x : S) cin >> x; for (int& x : G) cin >> x; vector power(M, 1); long long states = 1; bool too_large = false; for (int i = 0; i < M; ++i) { if (states > MAX_STATES / N) { too_large = true; break; } if (i + 1 < M) { power[i + 1] = power[i] * N; } states *= N; } if (too_large) { cerr << "State space is too large: N = " << N << ", M = " << M << '\n'; return 1; } auto encode = [&](const vector& P) { long long id = 0; for (int i = 0; i < M; ++i) { id += 1LL * (P[i] - 1) * power[i]; } return id; }; long long start = encode(S); long long goal = encode(G); vector visited(states, false); queue que; visited[start] = true; que.push(start); bool answer = false; vector P(M); while (!que.empty()) { long long state = que.front(); que.pop(); if (state == goal) { answer = true; break; } long long x = state; for (int i = 0; i < M; ++i) { P[i] = x % N + 1; x /= N; } // F 階のボタンを押す。 for (int F = 1; F <= N; ++F) { int min_distance = N; for (int i = 0; i < M; ++i) { min_distance = min(min_distance, abs(P[i] - F)); } // 最短距離の台が複数あれば、 // そのどれを選ぶ遷移もすべて試す。 for (int i = 0; i < M; ++i) { if (abs(P[i] - F) != min_distance) { continue; } long long next_state = state + 1LL * (F - P[i]) * power[i]; if (!visited[next_state]) { visited[next_state] = true; que.push(next_state); } } } } cout << (answer ? "Yes\n" : "No\n"); } }