import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	PrintWriter out = new PrintWriter(System.out);
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer tok = new StringTokenizer("");
    String next() throws IOException {
        if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); }
        return tok.nextToken();
    }
    int ni() throws IOException { return Integer.parseInt(next()); }
    long nl() throws IOException { return Long.parseLong(next()); }
    
    static int mv= 1000000001;
    
    void solve() throws IOException {
        for (int TC=ni();TC>0;TC--) {
            int n=ni();
            int[][]A=new int[n][2];
            int[]C=new int[n];
            for (int x=0;x<n;x++) { A[x][0]=ni(); A[x][1]=ni(); }
            Arrays.sort(A,(a,b)->Integer.compare(a[0],b[0]));
            for (int x=0;x<n;x++) C[x]=A[x][1];
            
            ArrayList<Integer> D = new ArrayList();
            int c=0;
            for (int x=n-1;x>=0;x--) {
                if (A[x][0]>x+c) { c++; D.add(x); }
            }
            
            long ans=0;
            BIT bit=new BIT(n,C);
            for (int x=0;x<D.size();x++) {
                int y=bit.chkBIT(0,D.get(x),n-1);
                bit.remBIT(0,y,D.get(x),n-1);
                ans+=y;
            }
            out.println(ans);
        }
        out.flush();
    }
    
    class BIT {
        int n;
        int[] A;
        int[] BT;
        int[] R;
        int[] L;
        int[] M;
        
        BIT(int a, int[] A) {
            n=a;
            this.A=A;
            int p=1;
            while (a>0) { p*=2; a=a>>1; }
            BT=new int[p*2];
            R=new int[p*2];
            L=new int[p*2];
            M=new int[p*2];
            makeBT(0,0,n-1);
        }
        
        int chkBIT(int v, int l, int r) {
            //if (l==r) return BT[v];
            if (l==L[v] && r==R[v]) return BT[v];
            if (l>M[v]) return chkBIT(v*2+2,l,r);
            if (r<=M[v]) return chkBIT(v*2+1,l,r);
            return Math.min(chkBIT(v*2+1,l,M[v]),chkBIT(v*2+2,M[v]+1,r));
        }
        
        boolean remBIT(int v, int u, int l, int r) {
            if (u<BT[v]) return false;
            if (l==r) { BT[v]=mv; return true; }
            if (l>M[v]) remBIT(v*2+2,u,l,r);
            if (r<=M[v]) remBIT(v*2+1,u,l,r);
            if (l<=M[v] && r>M[v]) {
                if (!remBIT(v*2+1,u,l,M[v])) remBIT(v*2+2,u,M[v]+1,r);
            }
            BT[v]=Math.min(BT[v*2+1],BT[v*2+2]);
            return true;
        }
        
        int makeBT(int v, int l, int r) {
            L[v]=l;
            R[v]=r;
            M[v]=(r+l)/2;
            if (l==r) BT[v]=A[r];
            else BT[v]=Math.min(makeBT(v*2+1,l,M[v]),makeBT(v*2+2,M[v]+1,r));
            return BT[v];
        }
    }
    
    public static void main(String[] args) throws IOException {
        new Main().solve();
    }
}