package com.company.real;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class JimuYouxi_20190510 {
static int T,N,L;
static long[] LDS_TREE,MAX_TREE;
static long A;
static Node0510[] nodes;
public static void main(String[] args) throws Exception{
System.setIn(new FileInputStream("C:\\Users\\XAGDC\\Desktop\\sw\\27Pro 积木游戏Block Game\\eval_input.txt"));
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(reader.readLine());
int T=Integer.parseInt(st.nextToken());//测试用例的个数
for (int z = 0; z <T ; z++) {
A=0;
st=new StringTokenizer(reader.readLine());
int N=Integer.parseInt(st.nextToken());//一共有N个节点
nodes=new Node0510[N];
for (int zz = 0; zz < N; zz++) {
st=new StringTokenizer(reader.readLine());
nodes[zz]=new Node0510(zz,Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
}
L=1;
while(L<N){
L=L+L;
}
LDS_TREE=new long[2*L];
MAX_TREE=new long[2*L];
//构建最大树
for (int i = 0; i <N ; i++) {//构建最大树,这块其实可以直接遍历一下
update(L+nodes[i].index,nodes[i].value,MAX_TREE);
}
Arrays.sort(nodes);
//构建LDS树
for (int i = 0; i <N ; i++) {
long value=query(L,L+nodes[i].index-1,LDS_TREE)+nodes[i].value;
long max=query(L+nodes[i].index+1,L*2-1,MAX_TREE);
A=Math.max(A,(value+max));
update(L+nodes[i].index,value,LDS_TREE);
}
System.out.printf("#%d %d\n",z,A);
}
reader.close();
}
static void update(int index,long value,long[]datas){
while(index>0 && value>datas[index]){//这块是取最大的
datas[index]=value;
index=index>>1;
}
}
static long query(int start,int end,long[] datas){
long res=0;
while(start<=end){
if(start%2==1){
res=Math.max(res,datas[start]);
}
if(end%2==0){
res=Math.max(res,datas[end]);
}
start=(start+1)>>1;
end=(end-1)>>1;
}
return res;
}
}
class Node0510 implements Comparable<Node0510> {
int index;
int weight;
int value;
public Node0510(int index, int weight, int value) {
this.index = index;
this.weight = weight;
this.value = value;
}
@Override
public int compareTo(Node0510 o) {//weight递减 weight一样的话,index递减
if(this.weight!=o.weight){
return o.weight-this.weight;
}else{
return o.index-this.index;
}
}
}