def main():
    import sys
    from operator import itemgetter
    from collections import defaultdict
    input = sys.stdin.readline

    t = int(input())
    for _ in range(t):
        N = int(input())
        MP = []
        p_list = []
        for _ in range(N):
            m, p = map(int, input().split())
            MP.append([m, p])
        MP.sort(key=itemgetter(0))
        p_idx = defaultdict(list)
        for i in range(N):
            p = MP[i][1]
            p_idx[p].append(i)
        p_list = list(p_idx.keys())
        p_list.sort()

        i = 0
        voted = 0
        bribed = []
        while True:
            if MP[i][0] <= voted:
                i += 1
                voted += 1
                if i == N:
                    break
            else:
                break
        if i == N:
            print(0)
            continue
        for p0 in p_list:
            for j in p_idx[p0]:
                if j < i:
                    continue
                bribed.append(MP[j])
                voted += 1
                MP[j][0] *= -1
                while True:
                    if MP[i][0] <= voted:
                        if MP[i][0] >= 0:
                            voted += 1
                        i += 1
                        if i == N:
                            break
                    else:
                        break
                #print(t, p0, voted, i, MP)
                if i == N:
                    break
            if i == N:
                break
        L = len(bribed)
        ans = 0
        for m, p in bribed:
            if -m >= L:
                ans += p
        print(ans)


if __name__ == '__main__':
    main()
