#include <iostream>
#include <climits>
#include <cstring>
using namespace std;
int main() {
int T=0;
scanf("%d",&T);
for(int i=0;i<T;i++) {
int minIn=INT_MAX, maxOut=INT_MIN;
string strIn,strOut;
int N=0;
scanf("%d",&N);
while(N--) {
string str;
cin>>str;
int h1,m1,s1,h2,m2,s2;
scanf("%d:%d:%d,%d:%d:%d",&h1,&m1,&s1,&h2,&m2,&s2);
int tempIn = h1*3600 + m1*60 +s1;
int tempOut = h2*3600 + m2*60 +s2;
if(tempIn<minIn) {
minIn = tempIn;
strIn = str;
}
if(tempOut>maxOut) {
maxOut = tempOut;
strOut = str;
}
}
strIn.pop_back();
strOut.pop_back();
cout<<strIn<<", "<<strOut<<endl;
}
return 0;
}