#include <bits/stdc++.h>
using namespace std;
int main( )
{
int tests;
cin >> tests;
while ( tests-- ) {
vector< pair< int ,int >> books;
vector< int > smallest;
int prev= - 1 ;
long long curr= 0 ;
long long rem= 0 ;
long long total= 0 ;
int num;
cin >> num;
for ( int i= 0 ; i< num; i++ ) {
int auth,happ;
cin >> auth>> happ;
books.push_back ( make_pair( auth,happ) ) ;
}
sort( books.begin ( ) ,books.end ( ) ) ; //Groups books by same author together. Within the same groups, books are sorted from smallest happiness to largest happiness.
for ( const auto & book : books) {
if ( book.first == prev) {
rem+ = book.second ;
} else {
smallest.push_back ( book.second ) ;
prev= book.first ;
}
}
//pick smallest book from each author
sort( smallest.begin ( ) ,smallest.end ( ) ) ; //sort these books from smallest to largest.
for ( const auto & small: smallest) {
total+ = ( ++ curr) * small;
}
total+ = rem* curr;
cout << total<< '\n ' ;
}
return 0 ;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CiAKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKIAppbnQgbWFpbigpCnsKCWludCB0ZXN0czsKCWNpbj4+dGVzdHM7Cgl3aGlsZSh0ZXN0cy0tKSB7CgkJdmVjdG9yPHBhaXI8aW50LGludD4+IGJvb2tzOwoJCXZlY3RvcjxpbnQ+IHNtYWxsZXN0OwoJCWludCBwcmV2PS0xOwoJCWxvbmcgbG9uZyBjdXJyPTA7CgkJbG9uZyBsb25nIHJlbT0wOwoJCWxvbmcgbG9uZyB0b3RhbD0wOwoJCWludCBudW07CgkJY2luPj5udW07CgkJZm9yKGludCBpPTA7aTxudW07aSsrKSB7CgkJCWludCBhdXRoLGhhcHA7CgkJCWNpbj4+YXV0aD4+aGFwcDsKCQkJYm9va3MucHVzaF9iYWNrKG1ha2VfcGFpcihhdXRoLGhhcHApKTsKCQl9CgkJc29ydChib29rcy5iZWdpbigpLGJvb2tzLmVuZCgpKTsgLy9Hcm91cHMgYm9va3MgYnkgc2FtZSBhdXRob3IgdG9nZXRoZXIuIFdpdGhpbiB0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