import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
for (int i = 0; i < N; i++) {
int m = sc.nextInt();
String[] records = new String[m+1];
for (int j = 0; j < m+1; j++) {
records[j] = sc.nextLine();
}
String[] record ;
Date early,late;
DateFormat df = new SimpleDateFormat("HH:mm:ss");
String first=null,last=null ;
try {
early = df.parse("23:59:59");
late = df.parse("00:00:00");
for (int j = 1; j < m+1; j++) {
record = records[j].split(" ");
if(early.compareTo(df.parse(record[1]))>0){
early = df.parse(record[1]);
first = record[0];
}
if(late.compareTo(df.parse(record[2]))<0){
late = df.parse(record[2]);
last = record[0];
}
}
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(first+" "+last);
}
}
}