#include "bits/stdc++.h"

using namespace std;

using ll = long long;
using pii = pair <int, int>;
using pll = pair <ll, ll>;

#define FIO() ios_base::sync_with_stdio(0);cin.tie(NULL);

string orig = "0123456789";
string nw = "015xx2xx8x";
map <char, char> mp;

int main() {
    FIO();

    for (int i = 0; i < 10; i++) mp[orig[i]] = nw[i];

    int tc; cin >> tc;
    while (tc--) {
        int h, m;
        cin >> h >> m;

        int sh, sm;
        cin >> sh;
        char temp; cin >> temp;
        cin >> sm;

        for (int tim = 0; tim < h * m; tim++) {
            int tm = sm, th = sh;
            tm += tim;
            th += (tm / m);

            tm = tm % m;
            th = th % h;

            string strh = "", strm = "";
            strh = to_string(th), strm = to_string(tm);
            if (strh.size() == 1) strh = "0" + strh;
            if (strm.size() == 1) strm = "0" + strm;

            reverse(strh.begin(), strh.end());
            reverse(strm.begin(), strm.end());

//            cout << strh << " " << strm << '\n';

            swap(strh, strm);

            bool ok = true;
            for (char& c : strh) {
                c = mp[c];
                if (c == 'x') {
                    ok = false;
                    break;
                }
            }

            if (!ok) continue;
            for (char& c : strm) {
                c = mp[c];
                if (c == 'x') {
                    ok = false;
                    break;
                }
            }

            if (!ok) continue;

            if (stoi(strh) < h and stoi(strm) < m) {
                strh = "", strm = "";
                strh = to_string(th), strm = to_string(tm);
                if (strh.size() == 1) strh = "0" + strh;
                if (strm.size() == 1) strm = "0" + strm;

                cout << strh << ":" << strm << '\n';
                break;
            }
        }
    }
}
