#include <iostream>
#include <cstdio>
#define int long long
using namespace std;

int t , n;
int a[500010] , b[500010];
int fa[500010];
const int mod = 1e9 + 7;
bool mp[500010];

void init(){
	for(int i=1;i<=n;i++)
		fa[i] = i;
}

int find(int x){
	if(x == fa[x])return x;
	return fa[x] = find(fa[x]);
}

int ksm(int A,int B){
	int temp = 1;
	for(;B;B>>=1 , A = A * A % mod)
		if(B & 1)
			temp = temp * A % mod;
	return temp;
}

signed main(){
	scanf("%lld" , &t);
	while(t --){
		scanf("%lld" , &n);
		for(int i=1;i<=n;i++)
			mp[i] = 0;
		init();
		for(int i=1;i<=n;i++)
			scanf("%lld" , &a[i]);
		for(int i=1;i<=n;i++)
			scanf("%lld" , &b[i]);
		for(int i=1;i<=n;i++){
			int na = find(a[i]) , nb = find(b[i]);
			fa[na] = nb;
		}
		int ans = 0;
		for(int i=1;i<=n;i++){
			int now = find(i);
			if(!mp[now]){mp[now] = 1;ans++;}
		}
		int sum = ksm(2 , ans);
		printf("%lld\n" , sum);   
	}
	return 0;
}
	