/*
   ／＞  フ
   |  _  _|
   ／`ミ _x 彡
   /      |
  /   ヽ   ﾉ
 ／￣|   | | |
 | (￣ヽ＿_ヽ_)_)
 ＼二つ
 */
 
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <string>
#include <map>
#include <set>
#include <cassert>
#include <ciso646>
#include <climits>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <array>
#include <bitset>
#include <deque>
#include <forward_list>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <algorithm>
#include <complex>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <limits>
#include <locale>
#include <numeric>
 
#include <regex>
#include <string>
#include <utility>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <random>
#include <memory>
#include <chrono>
  using namespace std;
const unsigned long long inf = 1e18;
#define MAXN 7000
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
using ll = long long;
#define int long long
#define endl '\n'
ll mod = 1e9 + 7;
void solve() {
  int n; cin >> n;
  vector <int> a(n);
  vector <int> b(n);
  vector <int> d(n);
  vector <int> e(n);
  for (int i = 0; i < n; i++) {
    cin >> a[i]; a[i]--;
    d[a[i]] = i;
  }
  for (int i = 0; i < n; i++) {
    cin >> b[i]; b[i]--;
    e[b[i]] = i;
  }
  int ans = 0;
  vector <int> g(n, 0);
    for (int i = 0; i < n; i++) {
        if (g[i]) continue;
        int j = d[b[i]];
        ans++;
        while (a[j] != a[i]) {
            g[j] = 1;
            j = d[b[j]];
        }
    }
    int k = 1;
    for (int i = 0; i < ans; i++) {
        k = (2 * k) % (mod);
    }
  cout << k << endl;
}
 
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0); cout.tie(0);
  ll t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
