#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
vector<int> visited(400001);
vector<vector<int>> edges(400001);
int mod = 1000000007;
void dfs(int indx){
    visited[indx] = 1;
    for (int child : edges[indx]){
        if (visited[child] == 0){
            dfs(child);
        }
    }
}
void solve(){
    int n;
    cin>>n;
    for (int i=1;i<=n;i++){
        visited[i] = 0;
        edges[i].clear();
    }
    vector<pair<int,int>> inp(n);
    for (int i=0;i<n;i++){
        cin>>inp[i].first;
    }
    for (int i=0;i<n;i++){
        cin>>inp[i].second;
    }
    for (int i=0;i<n;i++){
        int x = inp[i].first , y = inp[i].second;
        edges[x].push_back(y);
        edges[y].push_back(x);
    }
    int res = 0;
    for (int i=1;i<=n;i++){
        if (visited[i] == 0){
            dfs(i);
            res++;
        }
    }
    int ans = 1;
    while (res != 0){
        ans *= 2;
        ans %= mod;
        res--;
    }
    cout<<ans<<endl;
}
int32_t main(){
IOS;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
    int t = 1;
    cin>>t;
    while (t--){
        solve();
    }
}
