#include #include using namespace std; #define ll long long const ll mod = 1e9 + 7; ll fac[200010], inv[200010]; ll mypow(ll a, ll b) { ll ret = 1; while (b) { if (b & 1)ret = ret * a%mod; a = a * a%mod; b >>= 1; } return ret; } void init() { fac[0] = 1; for (int i = 1; i < 200010; i++)fac[i] = fac[i - 1] * i%mod;; inv[200010 - 1] = mypow(fac[200010 - 1], mod - 2); for (int i = 200010 - 1; i >= 1; i--)inv[i - 1] = inv[i] * i%mod; /* for (int i = 0; i <= 10; i++) { cout << i << " " << fac[i] << " " << inv[i] << endl; } */ } ll C(int n, int m) { return fac[n] * inv[m] % mod*inv[n - m] % mod; } int a[200010]; int b[200010]; int c[200010]; int flg[200010]; int main() { ios::sync_with_stdio(0); cin.tie(0); init(); int t; cin >> t; while (t--) { int n; cin >> n; int p = 0; for (int i = 1; i <= 2 * n; i++)c[i] = flg[i] = 0; for (int i = 1; i <= n; i++) { int x, y; cin >> x >> y; if (x == y)c[x]++; else { a[++p] = x; b[p] = y; } } ll ans = mypow(2,p); for (int i = 1; i <= p; i++) { if (flg[a[i]] != 2)flg[a[i]] = 1; if (flg[b[i]] != 2)flg[b[i]] = 1; if (i!=p && b[i] == a[i + 1]) { flg[b[i]] = 2; } } /* for (int i = 1; i <= p; i++) { cout << a[i] << " " << b[i] << endl; } for (int i = 1; i <= 2 * n; i++) { cout << c[i] << flg[i] << endl; } */ for (int i = 1; i <= 2 * n; i++) { if (flg[i]==2) { //cout << "2 " << i << endl; ans *= (C(2 * c[i] + 2, c[i]) + C(2 * c[i] + 2, c[i] + 1))*inv[2]%mod; } else if (flg[i] == 1) { //cout << "1 " << i << endl; ans *= C(2 * c[i] + 1, c[i] + 1) % mod; } else { ans *= C(2 * c[i], c[i]); //cout << "0 " << i << endl; } ans %= mod; } cout << ans << endl; } }