#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin >> t;
    while(t--)
    {


    string s;
    char check[5]={'0','1','2','5','8'};
    int h,m;
    cin >> h >> m;
    cin >> s;
    int sum1 = 0,sum2=0;
    int i;
    for( i=0;i<s.size();i++)
    {
        if(s[i]==':')
            break;
        sum1 = sum1*10 + (s[i]-'0');
    }
    for(++i;i<s.size();i++)
    {
        sum2 = sum2*10 + (s[i]-'0');
    }
    int ok1 = 0,ok2 = 0;
    string str1,str2,t1,t2;

    while(ok2==0 || ok1==0)
    {

        str2 = to_string(sum2);


        if(str2.size()==1){
            str2+="0";
            reverse(str2.begin(),str2.end());
            str2[0] = '0';
        }
        t2 = str2;



        for(int i=0;i<str2.size();i++)
        {

            if(str2[i]==check[0] || str2[i]==check[1] || str2[i]==check[2] || str2[i]==check[3] || str2[i]==check[4])
            {
                if(i==1)
                {



                    if(str2[0]=='2') str2[0] = '5';
                    else if(str2[0]=='5') str2[0] = '2';
                    if(str2[1]=='2') str2[1] = '5';
                    else if(str2[1]=='5') str2[1] = '2';

                    reverse(str2.begin(),str2.end());
                    int p = stoi(str2);


                     if(p>=0 && p<=h-1){

                        ok2=1;

                     }
                     else
                     {
                         str2 = t2;
                     }

                }
            }
            else
                break;

        }

        str1 = to_string(sum1);


        if(str1.size()==1){
            str1+="0";
            reverse(str1.begin(),str1.end());
            str1[0] = '0';
        }
           t1 = str1;

        for(int i=0;i<str1.size();i++)
        {
            if(str1[i]==check[0] || str1[i]==check[1] || str1[i]==check[2] || str1[i]==check[3] || str1[i]==check[4])
            {
                if(i==1)
                {
                    //cout<<str1;
                    if(str1[0]=='2') str1[0] = '5';
                    else if(str1[0]=='5') str1[0] = '2';
                    if(str1[1]=='2') str1[1] = '5';
                    else if(str1[1]=='5') str1[1] = '2';

                    reverse(str1.begin(),str1.end());
                    int p = stoi(str1);


                     if(p>=0 && p<=m-1){
                        ok1=1;
                     }
                     else
                     {
                         str1 = t1;
                     }


                }
            }
            else
                break;

        }
      //  cout<<sum2<<" "<<sum1<<" "<<ok2<<" "<<ok1<<endl;
        if(ok2==0 || ok1 ==0 ){

            sum2 = (sum2 + 1)%m;
            ok2 = 0;

            if(sum2==0)
            {
                sum1 = (sum1 + 1) %h;
                ok1 = 0;
            }
        }
    }



    cout<<t1<<":"<<t2<<endl;
    }

    return 0;
}
