#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <utility>
#include <functional>
#include <bitset>
#include <iomanip>
#include <ctime>
#include <cstdio>
#include <cstring>
#include <chrono>
#include <complex>
#define endl "\n"
#define ll long long int
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define pii pair<int,int>
#define vi vector<int>
#define vll vector<ll>
#define vvi vector < vi >
#define all(v) v.begin(),v.end()
using namespace std;
ll max(ll a ,ll b);
ll min(ll a ,ll b);
ll gcd(ll a, ll b);
ll lcm(ll a, ll b);
const int mod = 1000000007;
void solve() {
int n;cin >> n;
vector<pii> v;
ll a,b,last,x;
for(int i = 0;i<n;++i) {
cin >> a >> b;
v.pb({a,b});
}
sort(all(v));
ll c = 1,ans = 0;
ll took = 0;
for(int i = 0;i<n;++i) {
c = v[i].first;
took = 0;
vector<pair<ll,ll>> temp;
while(i<n && v[i].first==c) {
temp.push_back({v[i].second,v[i].first});
i++;
}
i--;
sort(temp.rbegin(),temp.rend());
int j = 0;
x = temp.size();
for(j = 0;j<x && j<c-took;++j) {
ans+=(temp[j].first);
}
}
cout << ans << endl;
}
int main(){
std::ios::sync_with_stdio(false);
int T;
cin>>T;
while(T--)
{
solve();
}
return 0;
}
ll max(ll a,ll b){
return (a>b)?a:b;
}
ll min(ll a ,ll b){
return (a<b)?a:b;
}
ll gcd(ll a ,ll b){
if(b==0) return a;
return gcd(b,a%b);
}
ll lcm(ll a ,ll b){
return (a*b)/gcd(a,b);
}
807A - Is it rated | 1096A - Find Divisible |
1430C - Numbers on Whiteboard | 1697B - Promo |
208D - Prizes Prizes more Prizes | 659A - Round House |
1492C - Maximum width | 171B - Star |
1512B - Almost Rectangle | 831B - Keyboard Layouts |
814A - An abandoned sentiment from past | 268C - Beautiful Sets of Points |
1391C - Cyclic Permutations | 11A - Increasing Sequence |
1406A - Subset Mex | 1365F - Swaps Again |
50B - Choosing Symbol Pairs | 1719A - Chip Game |
454B - Little Pony and Sort by Shift | 1152A - Neko Finds Grapes |
1719B - Mathematical Circus | 1719C - Fighting Tournament |
1642A - Hard Way | 285C - Building Permutation |
1719E - Fibonacci Strings | 1696C - Fishingprince Plays With Array |
1085A - Right-Left Cipher | 1508B - Almost Sorted |
1690C - Restoring the Duration of Tasks | 1055A - Metro |