/******************************************
* AUTHOR : SARTHAK M. Das *
* NICK : Sythe *
* INSTITUTION : BIT MESRA *
******************************************/
#include <bits/stdc++.h>
using namespace std;
#define LL long long
#define N 100005
#define MOD 1000000007
#define dd double
#define rep(i, n) for(int i = 0; i < n; i++)
#define REP(i,a,b) for(int i=a;i<b;i++)
#define rep1(i,b) for(int i=1;i<=b;i++)
#define pb push_back
#define mp make_pair
#define clr(x) x.clear()
#define sz(x) ((int)(x).size())
#define F first
#define S second

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	//ios_base& scientific (ios_base& str);
	int t;
	cin>>t;
	while(t--){
		LL n;
		cin>>n;
		vector<pair<LL,LL>> v(n,mp(0,0));

		rep(i,n){
			cin>>v[i].F;
			v[i].F=v[i].F-1;
		}


		rep(i,n){
			cin>>v[i].S;
			v[i].S=v[i].S-1;
		}
		sort(v.begin(),v.end());

		vector<LL> vis(n,-1);
		LL c=0;
		for(LL i=0;i<n;i++)
		{
			if(vis[i]==1)
				continue;

			c++;
			LL x=v[i].F;
			LL y=v[i].S;
			vis[x]=1;
			while(vis[y]==-1){
				x=y;
				y=v[y].S;
				vis[x]=1;
			}
		}
		LL r=1;
		for(int i=0;i<c;i++)
		{
			r=(r*2)%MOD;
		}
		cout<<r<<endl;

	}
	return 0;
}