
#include<bits/stdc++.h>
using namespace std;
#include<cstring>
#include<vector>
typedef long long int ll;
typedef long double ld;
typedef double db;

 ll solve(ll i,ll h)
 {
     ll a[10]={0,1,5,-1,-1,2,-1,-1,8,-1};
     ll b=i/10,c=i%10;
     if(  a[b]!=-1 && a[c]!=-1 )
     {
         ll ch= 10*( a[c] )+a[b];

         if(ch<h){return i; }
         else { return -1;}
     }
     else {return -1;}
 }


int main()
{
    ll tt;cin>>tt;
    for(ll ii=0;ii<tt;ii++)
    {
       ll h,m,cm=0,ch=0,am=0,ah=0;cin>>h>>m;
       string s;cin>>s;
       ll hrs= (int(s[0] )-48)*10 +   int(s[1])-48;
       ll mnt= (int(s[3] )-48)*10 +int(s[4])-48;

       for( ll i=mnt;i<m;i++  )
       {
           ll d= solve(i ,h);
           if(d!=-1 ){cm=1;am=d;break;  }
       }

       if(cm==0){am=0;hrs++; }
       for( ll i=hrs;i<h;i++  )
       {
           ll t= solve(i ,m);
           if(t!=-1 ){ch=1;ah=t;break;  }
       }

       if(hrs!=ah ){ am=0;}


        if(ah==0){ cout<<ah<<ah;  }
        else if(ah>0 && ah<10){ cout<<0<<ah;  }
        else{  cout<<ah; }
        cout<<":";

        if(am==0){ cout<<am<<am;  }
        else if(am>0 && am<10){ cout<<0<<am;  }
        else{  cout<<am; }
        cout<<endl;



    }
}
