    #include<bits/stdc++.h>
    
    using namespace std;
    
    #define rep(i,k,n) for(i=k;i<n;i++)
    #define repr(i,k,n) for(i=k;i>=n;i--)
    #define inf(i,s) for(i=s;;i++)
    #define ll long long
    #define pb(i) push_back(i)
    #define pop pop_back();
    #define all(s) s.begin(),s.end()
    #define maxl 9223372036854775807
    #define up upper_bound
    #define lb lower_bound
    #define mod 1000000007
    #define vll vector<ll>
    #define mkp make_pair
    
    template <typename T>
    inline void debug(vector<T> v){cout << "\ndebug(vector)\n"; ll i; rep(i, 0, v.size())cout << v[i] << " "; cout << "\n\n";} // debug<ll>(v);
    
    
    inline bool prime(ll n){
        ll i;
        for(i=2;i*i<=n;i++)
            if(n%i==0)
                return false;
        return true;
    }
    int unitPlace(int n)
        {return n%10;}
    int tensPlace(int n)
        {return n/10;}

    int h,m;
    vll v={0,1,5,-1,-1,2,-1,-1,8,-1};
    bool check(int hour,int mins)
    {
        if (v[tensPlace(hour)] < 0)
		return false;
	if (v[unitPlace(hour)] < 0)
		return false;
	if (v[tensPlace(mins)] < 0)
		return false;
	if (v[unitPlace(mins)] < 0)
		return false;
 
	int hr = v[unitPlace(mins)] * 10 + v[tensPlace(mins)];
	int ms = v[unitPlace(hour)] * 10 + v[tensPlace(hour)];
	return hr < h && ms < m;
    }
    int main(void)
    {
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        
        ll t; cin>>t;
        while(t--)
        {
            string s;
            cin>>h>>m>>s;
            int hour = stoi(s.substr(0,2));
            int mins  = stoi(s.substr(3,5));

            while(true)
            {
                if(check(hour,mins))
                {
                    cout<<tensPlace(hour)<<unitPlace(hour)<<":"<<tensPlace(mins)<<unitPlace(mins)<<endl;
                    break;
                }
                else
                {
                    mins++;
                    if(mins==m)
                    {
                        mins=0;
                        hour=((hour+1)%h);
                    }
                }  
            }
           
        }

        return 0;
    }