#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl ("\n")

void solve()
{
    ll h,m;
    cin>>h>>m;
    string s;
    cin>>s;
    ll H = (s[0]-'0')*10 + s[1]-'0';
    ll M = (s[3]-'0')*10 + s[4]-'0';
    ll a[] = {0,1,5,-1,-1,2,-1,-1,8,-1};
    for(ll i=H;i<h;i++)
    {
        for(ll j=0;j<m;j++)
        {
            ll p = i/10;
            ll q = i%10;
            ll r = j/10;
            ll t = j%10;
            if(a[p]==-1 || a[q]==-1 || a[r]==-1 || a[t]==-1)
                continue;
            p = a[p];
            q = a[q];
            r = a[r];
            t = a[t];
            ll h1 = t*10+r;
            ll m1 = q*10+p;
            if(h1<h && m1<m && ((i>H) || (i==H && j>=M)))
            {
                cout<<a[m1%10]<<a[m1/10]<<":"<<a[h1%10]<<a[h1/10]<<endl;
                return;
            }
        }
    }
    cout<<"00:00"<<endl;
}

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