#include<bits/stdc++.h>
using namespace std;
  
  
int findnext(int value){
  int checkarr[10]={0,1,5,-1,-1,2,-1,-1,8,-1};
    int tens = value/10;
    int ones = value%10;
    if(checkarr[tens]!=-1 && checkarr[ones]!=-1){
       return checkarr[ones]*10+checkarr[tens];
    }
    else{
      return -1;
    }
}

void cheack(){
    int h,m;
    cin>>h>>m;
    string str;
    cin>>str;
    int hour = (str[0]-'0')*10 + (str[1]-'0');
    int minute = (str[3]-'0')*10 + (str[4]-'0');
    
    while(1){
       if(minute==m){
         minute=0;
         hour++;
       }
       if(hour==h){
         hour=0;
       }
       //cout<<"this is it "<<hour<<":"<<minute<<endl;
       int finalhour = findnext(hour);
       int finalmin = findnext(minute);
       if(finalmin<h && finalhour<m && finalmin!=-1 && finalhour!=-1){
         if(hour<10){
           cout<<0;
         }
         cout<<hour<<":";
         if(minute<10){
           cout<<0;
         }
         cout<<minute<<endl;
         break;
       }
       minute++;
    }
}

int main()
{
    int t;
    cin>>t;
    while(t-->0){
      cheack();
    }
   return 0;
}