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

#define pb push_back
#define all(x) x.begin(), x.end()
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <typename T> using o_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename T, typename R> using o_map = tree<T, R, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
typedef long long ll;

#define inf 1e9
#define MOD 1000000007
#define vint vector<int>
#define vll vector<ll>
#define no cout << "NO" << endl;

void solve() {
  ll nby0 = 0 , nby1 = 0;
    ll n ; cin >> n ;
    vector < bool > fama0(n+1 , false ), fama1(n+1 , false );

    map < ll , ll > mp ;
    vector < ll > x0 , x1 ;
    ll ans= 0;
    for ( int i = 0 ; i < n; i++ ) {
        ll x  , y ; cin >> x >> y ;
        if (y == 0 ) {
            x0.pb(x );
            fama0[x] = 1 ;
            nby0 ++ ;
            continue ;
        }
        fama1[x] = 1 ;
        nby1++ ;
        x1.pb(x) ;
    }
    ll len0 = x0.size(), len1 = x1.size() ;
    ll mini0 = x0[0] , maxi0 = x0[len0-1] , mini1 = x1[0] , maxi1  = x1[len1 - 1 ] ;

    ll sofar0 = 0 , sofar1  = 0 ;
    for (int  x = 0 ; x<=  n ; x++) {
        if (fama0[x]) sofar0++;
        if ( fama1[x]) sofar1++ ;
        if (x >0  && x <n-1 && fama0[x] && fama1[x-1] && fama1[x+1]) ans++;
        if (x >0  && x <n-1 && fama1[x] && fama0[x-1] && fama0[x+1]) ans++;
        if (fama0[x] && fama1[x] ) ans+=(nby0 - 1 + nby1-1) ;
       // cout << ans << endl;
     }

    cout << ans << endl ;
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    int t = 1;
    cin >> t;
    while (t--) {
        solve();
    }

    return 0;
}
