from sys import stdin, stdout
import heapq

class MyHeap(object):
   def __init__(self, initial=None, key=lambda x:x):
       self.key = key
       if initial:
           self._data = [(key(item), item) for item in initial]
           heapq.heapify(self._data)
       else:
           self._data = []

   def push(self, item):
       heapq.heappush(self._data, (self.key(item), item))

   def pop(self):
       return heapq.heappop(self._data)[1]

   def print(self):
       for hd in self._data:
            print(hd)
       print('-------------------------------')

def getminnumerofcoins(n, mpa):

    res = 0

    mpa.sort(key=lambda x: (x[0], -x[1]))
    gap = []

    cur = 0
    for i in range(len(mpa)):
        mp = mpa[i]
        #print(mp[0])
        if mp[0] > cur:
            t = [i, mp[0]-cur]
            gap.append(t)
            #cur = mp[0]

        cur += 1

    #print(gap)

    if len(gap) == 0:
        return 0

    hp = MyHeap(key=lambda x: x[1])
    gp = gap.pop()
    lidx = gp[0]
    remaing = gp[1]
    for i in range(lidx, len(mpa)):
        ci = [i, mpa[i][1]]
        hp.push(ci)

    cur = 0
    offset = 0
    for i in range(len(mpa)):
        mp = mpa[i]
        need = mp[0] - cur

        if need > 0:
            for j in range(need):
                if (remaing == 0 or len(hp._data) == 0) and len(gap) > 0:
                    lg = gap.pop()
                    while len(gap) > 0 and lg[1] - offset <= 0:
                        lg = gap.pop()
                    for k in range(lg[0], lidx):
                        ci = [k, mpa[i][1]]
                        hp.push(ci)
                    lidx = lg[0]
                    remaing = lg[1] - offset

                c = hp.pop()
                #print(c)
                if c[0] == i:
                    c = hp.pop()
                    #print(c)
                res += c[1]
                cur += 1
                offset += 1
                remaing -= 1

        cur += 1

    return res


if __name__ == '__main__':
    t = int(stdin.readline())

    for i in range(t):
        n = int(stdin.readline())

        mpa = []
        for j in range(n):
            mp = list(map(int, stdin.readline().split()))
            mpa.append(mp)
        res = getminnumerofcoins(n, mpa)
        stdout.write(str(res) + '\n')
