#include<bits/stdc++.h>
#define int long long
#define double long double
#define sz(x) (int)(x).size()
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define x first
#define y second
using namespace std;
using pi = pair<int,int>;
const int inf = 0x3f3f3f3f3f3f3f3f;
const int minf = 0xc0c0c0c0c0c0c0c0;

inline int valid(int x) {
    if (x==0 || x==1 || x==2 || x==5 || x==8) return 1;
    return 0;
}

inline int f(int x) {
    if (x==2) return 5;
    if (x==5) return 2;
    return x;
}

signed main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int TC; cin>>TC;
    for (int tc=1; tc<=TC; tc++) {
        int h,m; cin>>h>>m;
        char dummy;
        int H,M; cin>>H>>dummy>>M;
        while (1) {
            if (valid(H/10) && valid(H%10) && valid(M/10) && valid(M%10)) {
                int TH = H, TM = M;
                swap(TH, TM);
                TH = f(TH%10)*10 + f(TH/10);
                TM = f(TM%10)*10 + f(TM/10);
                if (TH < h && TM < m) {
                    if (H<10) cout<<0<<H;
                    else cout<<H;
                    cout<<':';
                    if (M<10) cout<<0<<M;
                    else cout<<M;
                    cout<<'\n';
                    break;
                }
            }
            ++M;
            if (M==m) {
                ++H;
                M=0;
            }
            if (H==h) H=0;
        }
    }
    return 0;
}