#include <bits/stdc++.h>
#define int long long

using namespace std;

int t, h, m;
char trash;

int refdigit(int d) {
    if (d == 0) return 0;
    if (d == 1) return 1;
    if (d == 2) return 5;
    if (d == 3) return -1;
    if (d == 4) return -1;
    if (d == 5) return 2;
    if (d == 6) return -1;
    if (d == 7) return -1;
    if (d == 8) return 8;
    if (d == 9) return -1;
    else return -1;
}

int ref(int a) {
    int x = a/10;
    int y = a%10;
    int x2 = refdigit(y);
    int y2 = refdigit(x);
    if (x2 == -1 || y2 == -1) return -1;
    return x2*10 + y2;
}

bool test(int x, int y) {
    int x2 = ref(y);
    int y2 = ref(x);
    return x2 >= 0 && y2 >= 0 && x2 < h && y2 < m;
}

int32_t main() {
    cin >> t;
    while (t--) {
        cin >> h >> m;
        int x, y;
        cin >> x >> trash >> y;
        while (!test(x, y)) {
            if (y == m-1) {
                x = (x+1) % h;
                y = 0;
            } else {
                y = (y+1) % m;
            }
        }
        if (x < 10) cout << "0";
        cout << x << ":";
        if (y < 10) cout << "0";
        cout << y << "\n";
    }
}
