#include using namespace std; struct node{ int val; int cnt; }; bool cmp(node a, node b){ return a.val < b.val; } int cal(int n){ return n*(n+1)/2; } int main() { int T; scanf("%d", &T); while(T--){ node s[26]; memset(s, 0, sizeof(s)); int n, sum = 0; scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d%d", &s[i].val, &s[i].cnt); sort(s, s+n, cmp); int ans = 0, first; for (int i = 0; i < n; ++i){ if (s[i].val >= 0){ first = i; break; } } int temp = 0; for (int i = first; i < n; ++i){ int num = cal(s[i].cnt+sum) - cal(sum); sum += s[i].cnt; ans += num * s[i].val; temp += s[i].val * s[i].cnt; } for (int i = first - 1; i >= 0; --i){ if (temp + s[i].val > 0){ int cc = s[i].cnt; while(cc--){ if (temp + s[i].val <= 0) break; temp += s[i].val; ans += temp; } } else break; } printf("%d\n", ans); } return 0; }