#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define F first
#define S second
const ll N = 1e6 + 200 ;
const ll MOD = 1e9 + 7 ;
const ll Inf = MOD * MOD ;
const long double eps = 1e-7;
const ll dx[] = {1 , 0 , -1 , 0};
const ll dy[] = {0 , 1 , 0 ,-1};
ll n , m , k , vis[N] , timer  , tt = 1 ;
pair < ll , ll > P[N] ;
vector < ll > adj[N] ;
void Dfs(ll u)
{
    vis[u] = true ;
    for(auto v : adj[u])
    {
        if(!vis[v])
        {
            Dfs(v) ;
        }
    }
}
void Solve()
{
    scanf("%lld",&n);
    for(int i = 1 ; i <= n ; ++i)
    scanf("%lld",&P[i].F) ;

    for(int i = 1 ; i <= n ; ++i)
    {
        scanf("%lld",&P[i].S) ;
        adj[P[i].F].push_back(P[i].S) ;
    }
    ll Ans = 1 ;
    for(int i = 1 ; i <= n ; ++i)
    {
        if(!vis[i])
        {
            Dfs(i) ;
            Ans *= 2 ;
            Ans %= MOD ;
        }
    }
    for(int i = 1 ; i <= n; ++i)
    {
        vis[i] = false ;
        adj[i].clear() ;
    }
    printf("%lld\n",Ans);
}
int main(){
   scanf("%lld",&tt);
    while(tt--){
     ++timer;
      Solve();
    }
}
//Section Time : 0 ;


