#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef pair<int, int> pii;

#define dbg(x...) \
    do {          \
        cout << #x << " -> "; \
        err(x);   \
    } while (0)

void err() {
    cout << endl;
}

template<class T, class... Ts>
void err(T arg, Ts... args) {
    cout << arg << ' ';
    err(args...);
}

void read() {}

template<class T, class... Ts>
void read(T &x, Ts &... xs) {
    T f = 1;
    char ch;
    x = 0;
    for (ch = getchar(); ch < '0' || ch > '9'; ch = getchar()) {
        if (ch == '-') f = -1;
    }
    for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
    x *= f;
    read(xs...);
}

mt19937 mt(chrono::steady_clock::now().time_since_epoch().count());
ll rng(ll l, ll r) {
    uniform_int_distribution<ll> uni(l, r);
    return uni(mt);
}

template <class T>
void myHash(T a[], int n, T w[] = nullptr) {
    set<T> st;
    for (int i = 0; i < n; i++) {
        st.insert(a[i]);
    }
    int tot = 0;
    map<T, int> mp;
    for (T x : st) {
        mp[x] = ++tot;
    }
    for (int i = 0; i < n; i++) {
        a[i] = mp[a[i]];
    }
    if (w != nullptr) {
        for (pair<T, int> p : mp) {
            w[p.second] = p.first;
        }
    }
}

template<class T>
void unique(vector<T> &v) {
    sort(v.begin(), v.end());
    v.erase(unique(v.begin(), v.end()), v.end());
}

const int maxn = 4e5 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;

int a[maxn], b[maxn];
int vis[maxn];
int p[maxn];

void run() {
    int n;
    read(n);
    for (int i = 1; i <= n; i++) read(a[i]);
    for (int i = 1; i <= n; i++) read(b[i]);

    for (int i = 1; i <= n; i++) {
        vis[i] = 0;
        p[a[i]] = i;
    }

    int tot = 0;
    for (int i = 1; i <= n; i++) {
        if (vis[i]) continue;
        tot++;
        int cur = i;
        while (!vis[i]) {
            vis[i] = tot;
            i = p[b[i]];
        }
    }
    ll ans = 1;
    for (int i = 0; i < tot; i++) {
        ans *= 2; ans %= mod;
    }
    printf("%lld\n", ans);
}

/*

*/

int main() {

    int T = 1;
    read(T);
    while (T--) {
        run();
    }

    return 0;
}