#include #include "atcoder/dsu" using i64 = long long; void solve() { int N; std::cin >> N; std::vector A(N), B(N); for (auto &e : A) { std::cin >> e; --e; } for (auto &e : B) { std::cin >> e; --e; } atcoder::dsu uft(N); for (int i = 0; i < N; ++i) uft.merge(i, A[i]); std::vector isUsed(N); std::vector cycleId(N), destination(N), sMi(N); bool isOk = true; for (const auto &vs : uft.groups()) { std::vector cycle; { int v = vs.front(); while (true) { if (isUsed[v]) { const auto itr = std::find(cycle.begin(), cycle.end(), v); cycle.erase(cycle.begin(), itr); break; } else { cycle.push_back(v); isUsed[v] = true; v = A[v]; } } } const int u = (int)cycle.size(); for (int i = 0; i < u; ++i) { cycleId[cycle[i]] = i; sMi[cycle[i]] = i; } auto add = [&](int i, int f) { const int a = cycleId[i], b = cycleId[f]; const int c = sMi[i]; int sb = a >= b ? (a - b) : (a + N - b); int sc = a >= c ? (a - c) : (a + N - c); if (sb < sc) sMi[i] = b; }; for (const auto f : vs) { int x = f; int cnt = 0; if (A[x] == B[f]) { continue; } while (A[A[x]] != B[f]) { x = A[x]; ++cnt; if (cnt > 2 * N) { isOk = false; break; } } if (not isOk) break; if (std::find(cycle.begin(), cycle.end(), f) != cycle.end()) { // in cycle destination[f] = A[x]; add(x, f); } else { continue; } } if (not isOk) break; bool h = false; for (int i = 0; i < u; ++i) { const int t = destination[cycle[i]]; int x = cycle[i]; while (x != t) { const int c = sMi[x], b = i; const int sb = x >= b ? (x - b) : (x + N - b), sc = x >= c ? (x - c) : (x + N - c); if (sb < sc) { h = true; break; } x = A[x]; } if (h) break; } if (h) isOk = false; if (not isOk) break; } std::cout << (isOk ? "Yes" : "No") << std::endl; } int main() { int T; std::cin >> T; while (T--) { solve(); } }