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

typedef long long int ll;
using ii= pair<ll,ll>;
#define fr(i,a,b) for(ll i=a;i<b;i++)
#define all(o) (o).begin(),(o).end()
#define F first
#define S second
#define MP make_pair
#define PB push_back
#define ld long double
#define eps 0.00000000001
#define mod 1000000007

class prioritize{
    public: bool operator() (ii &p1,ii &p2){
        return p1.F<p2.F;
    }
};

auto start_time= high_resolution_clock::now();
void time()
{
    #ifndef ONLINE_JUDGE
        auto stop_time= high_resolution_clock::now();
        auto duration= duration_cast<milliseconds>(stop_time-start_time);
        cout<<"run time: "<<duration.count()<<" ms"<<"\n";
    #endif
    return;
}

void ojudge()
{
	#ifndef ONLINE_JUDGE
        freopen("input1.txt","r", stdin);
        freopen("output1.txt","w",stdout);
    #endif

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);cout.tie(NULL);
    return;
}

vector<ll> v[400010];
vector<ll> vst(400010,0);

void dfs(ll node){
	for(auto it:v[node]){
		if(!vst[it]){
			vst[it]= 1;
			dfs(it);
		}
	}
}

ll powerm(ll a,ll b,ll m)
{
	ll ans= 1;
	while(b){

		if(b&1) ans= (ans*a+m)%m;
		a= (a*a+m)%m;
		b>>=1;
	}
	return ans;
}

int main()
{
    ojudge();
    

    ll t;
    cin>>t;

    while(t--){

    	ll n;
    	cin>>n;

    	ll ip[2][n];
    	fr(i,0,2){
    		fr(j,0,n) cin>>ip[i][j];
    	}

        fr(i,0,n){
        	v[ip[0][i]].PB(ip[1][i]);
        	v[ip[1][i]].PB(ip[0][i]);
        }

        ll cnt=0;
        fr(i,1,n+1){
        	if(!vst[i]){
        		vst[i]=  1;
        		dfs(i);
        		cnt++;
        	}
        }

        ll val= powerm(2,cnt,mod);
        cout<<val<<"\n";

        fr(i,0,n+1){
        	vst[i]= 0;
        	v[i].clear();
        }

    }



    time();
    return 0;
}
