#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
#define int long long int

bool isvalid( int H, int M, int h, int m )
{
    string hour = to_string(M);
    string minu = to_string(H);

    reverse(hour.begin(), hour.end());
    reverse(minu.begin(), minu.end());

    if( hour.length() == 1 )
        hour.push_back('0');
    
    if( minu.length() == 1 )
        minu.push_back('0');
    
    for( auto &v: hour )
    {
        if( v == '2' )
        {
            v = '5';
        }
        else
        {
            if( v == '5' )
                v = '2';
            else
            {
                if( !( v == '0' || v == '1' || v =='8' ) )
                    return false;
            }
        }      
    }

    for( auto &v: minu )
    {
        if( v == '2' )
        {
            v = '5';
        }
        else
        {
            if( v == '5' )
                v = '2';
            else
            {
                if( !( v == '0' || v == '1' || v =='8' ) )
                    return false;
            }
        }
    }

    int candH = stoi(hour), candM = stoi(minu);
    return candH <= h && candM <= m;
}


int32_t main()
{
    int T = 1;
    cin>>T;
    while( T-- )
    {
        int h, m;
        cin>>h>>m;
        string s;
        cin>>s;
        string ans = "00:00";

        int H, M, pos;

        H = stoi( s.substr(0, 2) );
        s.erase(0, 3 );
        M = stoi(s);

        int flag = 0;
        while( H < h )
        {
            while( M < m )
            {
                if( isvalid( H, M, h - 1, m - 1 ) )
                {
                    string hora = to_string(H), minu = to_string(M);
                    if( hora.length() < 2 ) 
                        hora = "0" + hora;
                    if( minu.length() < 2 ) 
                        minu = "0" + minu;
                    
                    ans = hora + ":" + minu;
                    flag = 1;
                    break;
                }
                M++;
            }

            if( flag == 1 )
                break;
            H++;
            M = 0;
        }

        cout<<ans<<endl;
    }

    return 0;
}
