#include #define int long long using namespace std; using ll = long long; void solve(); template void println(Args... args) { apply([](auto &&... args) { ((cout << args << ' '), ...); }, tuple(args...)); cout << '\n'; } int32_t main() { cin.tie(nullptr); ios_base::sync_with_stdio(false); int t = 1; cin >> t; for (int tc = 0; tc < t; ++tc) { solve(); } return 0; } struct DSU { vector sz, p; explicit DSU(int n) : sz(n, 1), p(n) { iota(p.begin(), p.end(), 0); } int get(int x) { return x == p[x] ? x : p[x] = get(p[x]); } bool unite(int x, int y) { x = get(x), y = get(y); if (x == y) return false; if (sz[x] > sz[y]) swap(x, y); sz[y] += sz[x]; p[x] = y; return true; } }; bool sub(vector in, vector a) { map pos; for (int i = 0; i < a.size(); ++i) pos[a[i]] = i; in.push_back(in.front()); int tot = 0; for (int i = 0; i + 1 < in.size(); ++i) { tot += pos[in[i + 1]] <= pos[in[i]]; } assert(tot > 0); return tot == 1; } void solve() { int n; cin >> n; vector a(n), b(n); for (int &x : a) cin >> x, --x; for (int &x : b) cin >> x, --x; if (a == b) return println("No"); vector ok1(n, 1); DSU dsu(n); for (int i = 0; i < n; ++i) { dsu.unite(i, a[i]); for (int j = a[i], cnt = 0; cnt < n + 3; j = a[j], cnt++) { if (j == i) ok1[i] = 0; } } vector ok2(n, 1); for (int i = 0; i < n; ++i) { { int x = a[i]; bool ok = x == b[i]; for (int k = 0; k < n + 3; ++k) { x = a[x]; ok |= x == b[i]; } if (!ok) return println("No"); } if (!ok1[i]) { ok2[i] = 1; for (int j = b[i], cnt = 0; cnt < n + 3; j = b[j], cnt++) { if (dsu.get(j) != dsu.get(i) || ok1[j]) return println("No"); if (j == i) ok2[i] = 0; } } else { ok2[i] = 1; } } vector checked(n); vector seen(n); for (int i = 0; i < n; ++i) { if (ok1[i] || ok2[i]) checked[i] = true; if (!checked[i]) { vector ac{i}, bc{i}; while (a[ac.back()] != ac.front()) ac.push_back(a[ac.back()]); while (b[bc.back()] != bc.front()) bc.push_back(b[bc.back()]); for (int x : bc) checked[x] = 1; for (int x : ac) if (seen[x]) return println("No"); bool ok = false; // for (int x : ac) if (a[x] == b[x]) ok = true; if (!ok) return println("No"); for (int x : ac) seen[x] = 1; if (!sub(bc, ac)) return println("No"); } } println("Yes"); }