#include <bits/stdc++.h>

using namespace std;

map<int, int> M = {{0, 0},
                   {1, 1},
                   {2, 5},
                   {3, -1},
                   {4, -1},
                   {5, 2},
                   {6, -1},
                   {7, -1},
                   {8, 8},
                   {9, -1}};
int T, HH, MM;
string s;

int reflect(int num) {
    if (M[num / 10] == -1 || M[num % 10] == -1)
        return -1;
    return M[num % 10] * 10 + M[num / 10];
}

bool valid(int hour, int minute) {
    hour = reflect(hour);
    minute = reflect(minute);
    if (hour == -1 || minute == -1)
        return false;
    swap(hour, minute);
    if (hour >= HH || minute >= MM)
        return false;
    return true;
}

int main() {
#ifdef ACM
    freopen("input", "r", stdin);
#endif
    cin >> T;
    while (T--) {
        cin >> HH >> MM >> s;
        int hour = (s[0] - '0') * 10 + s[1] - '0';
        int minute = (s[3] - '0') * 10 + s[4] - '0';
        while (!valid(hour, minute)) {
            minute++;
            if (minute == MM) {
                hour = (hour + 1) % HH;
                minute = 0;
            }
        }
        printf("%.02d:%.02d\n", hour, minute);
    }
}