#include <iostream>
#include <cstdio>
#include <cstring>

#define LL long long
#define MOD 1000000007

using namespace std;

inline int read(void) {
    int x = 0, c = getchar();
    while (!isdigit(c)) c = getchar();
    while (isdigit(c)) x = (x<<3) + (x<<1) + (c^48), c = getchar();
    return x;
}

int n, res = 0;
int a[400005], b[400005];
int ap[400005], bp[400005];
int vis[400005];

void point(int p) {
    if (vis[p]) return;
    vis[p] = 1;
    point(ap[b[p]]);
    point(bp[a[p]]);
}
//a: 4 1 6 5 3 2 7 8
//b: 5 6 1 7 4 8 3 2

//a: 2 6 5 1 4 3 7 8
//b: 3 8 7 5 1 2 4 6

inline void load(void) {
    for (int i = 1; i <= n; ++i) {
        if (vis[i] == 0) {
            ++res;
            point(ap[b[i]]);
            point(bp[a[i]]);
        }
    }
}

inline LL qpow(LL a, LL p) {
    LL res = 1 % MOD;
    while (p) {
        if (p&1) res = res * a % MOD;
        a = a * a % MOD;
        p >>= 1;
    }
    return res % MOD;
}

int main(void) {
    int T = read();
    while (T--) {
        n = read();
        for (int i = 1; i <= n; ++i) a[i] = read(), ap[a[i]] = i;
        for (int i = 1; i <= n; ++i) b[i] = read(), bp[b[i]] = i;

        res = 0;
        memset(vis, 0, sizeof(vis));
        load();
        //cout << res << endl;

        printf("%lld\n", qpow(2, res));
    }   
    return 0;
}