#include <bits/stdc++.h>
#define FOR(ii,aa,bb) for(int ii=aa;ii<bb;ii++)
#define for0(ii,bb) FOR(ii,0,bb)
#define for1(ii,bb) FOR(ii,1,bb+1)
#define pb push_back
#define mp make_pair
#define st first
#define nd second
#define pii pair<int,int>
#define piii pair<pii,int>
#define sp " "
#define nl "\n"
#define all(x) x.begin(),x.end()
#define fastio() ios_base::sync_with_stdio(0);cin.tie(0);
#define ll long long
#define int ll

using namespace std;

const int N = 400005;
const int INF = 1e15+5;
const int mod = 1e9+7;

int h,m;
map<int,int> inv;

void solve(){
    cin >> h >> m;
    string s;
    cin >> s;
    int a=(s[0]-'0')*10+s[1]-'0';
    int b=(s[3]-'0')*10+s[4]-'0';
    while(1){
        if(!a&&!b){
            cout << "00:00\n";
            break;
        }
        if(b==m){
            b=0;
            a++;
        }
        a%=h;
        int d=inv[(a%10)]*10+inv[a/10];
        int c=inv[(b%10)]*10+inv[b/10];
        if(c>=INF||d>=INF){
            b++;
            continue;
        }
        if(c<h&&d<m){
            if(a<10)
                cout << "0";
            cout << a << ":";
            if(b<10)
                cout << "0";
            cout << b << nl;
            break;
        }
        b++;
    }
}

int32_t main(){
    fastio()
    int tt=1;
    cin >> tt;
    inv[0]=0;
    inv[1]=1;
    inv[2]=5;
    inv[3]=INF;
    inv[4]=INF;
    inv[5]=2;
    inv[6]=INF;
    inv[7]=INF;
    inv[8]=8;
    inv[9]=INF;
    while(tt--)
        solve();
}
