#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef vector<vector<int>> graph;

#define pii pair <ll, ll>
//#define int ll
#define double long double
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define PI acos(-1.0)
#define F first
#define S second

int const INF = 1e18 + 5;
int const MOD = 1e15 + 7;

bool ok (char x) {
    if (x == '7' || x == '9' || x == '6' || x == '4' || x == '3') {
        return 0;
    }
    return 1;
}

string rev (string x) {
    char r[] = {'0', '1', '5', ' ', ' ', '2', ' ', ' ', '8', ' '};
    string neww = x;
    neww[0] = r[x[1] - '0'];
    neww[1] = r[x[0] - '0'];
    return neww;
}

void solve() {
    int h, m;
    cin >> h >> m;
    string ss;
    cin >> ss;
    string p1 = "";
    p1 += ss[0];
    p1 += ss[1];
    string p2 = "";
    p2 += ss[3];
    p2 += ss[4];
    int xx1 = stoi(p1);
    int xx2 = stoi(p2);
    for (int i = xx2; i < m; i++) {
        string s = "";
        s += p1;
        string nw = to_string(i);
        if (nw.size() == 1) {
            nw = "0" + nw;
        }
        s += nw;
        if (ok(s[0]) && ok(s[1]) && ok(s[2]) && ok(s[3])) {
            p1 = "";
            p1 += s[0];
            p1 += s[1];
            p2 = "";
            p2 += s[2];
            p2 += s[3];
            string np1 = rev(p1);
            string np2 = rev(p2);
            int x1 = stoi(np1);
            int x2 = stoi(np2);
            if (x1 < m && x2 < h) {
                cout << p1 << ':' << p2;
                return;
            }
        }
    }
    for (int j = xx1 + 1; j < h; j++) {
        p1 = to_string(j);
        if (p1.size() == 1) {
            p1 = "0" + p1;
        }
        for (int i = 0; i < m; i++) {
            string s = "";
            s += p1;
            string nw = to_string(i);
            if (nw.size() == 1) {
                nw = "0" + nw;
            }
            s += nw;
            if (ok(s[0]) && ok(s[1]) && ok(s[2]) && ok(s[3])) {
                p1 = "";
                p1 += s[0];
                p1 += s[1];
                p2 = "";
                p2 += s[2];
                p2 += s[3];
                string np1 = rev(p1);
                string np2 = rev(p2);
                int x1 = stoi(np1);
                int x2 = stoi(np2);
                if (x1 < m && x2 < h) {
                    cout << p1 << ':' << p2;
                    return;
                }
            }
        }
    }
    cout << "00:00";
}

signed main()
{
//  freopen ("input.txt", "r", stdin);
//  freopen ("output.txt", "w", stdout);
//    ios_base::sync_with_stdio(0);
//    cin.tie(NULL);
//    cout.tie(NULL);
//    cout << fixed << setprecision(11);
    int q = 1;
    cin >> q;
    while (q--) {
        solve();
        cout << endl;
    }
    return 0;
}
