#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define pll pair<ll, ll>

int rf[10], h, m;

bool isValid(string s) {
    int n = s.size();
    
    for(char &x : s) {
        if(x == ':') continue;
        if(rf[x - '0'] == -1) return false;
        else {
            x = '0' + rf[x - '0'];
        }
    }
    int mm = (s[1] - '0') * 10 + (s[0] - '0');
    int hh = (s[4] - '0') * 10 + (s[3] - '0');
    if(hh < h && mm < m) return true;
    return false;
}

void solve() {
    for(int i=0; i<10; ++i) rf[i] = -1;
    rf[0] = 0;
    rf[1] = 1;
    rf[2] = 5;
    rf[5] = 2;
    rf[8] = 8;

    cin >> h >> m;
    string s;
    cin >> s;
    int mm = (s[3] - '0') * 10 + (s[4] - '0');
    int hh = (s[0] - '0') * 10 + (s[1] - '0');
    while(true) {
        string temp;
        temp += '0'+((hh/10) % 10);
        temp += '0'+(hh % 10);
        temp += ':';
        temp += '0'+((mm/10) % 10);
        temp += '0'+(mm % 10);
        // cout << temp << "\n";
        if(isValid(temp)) {
            cout << temp << "\n";
            break;
        }
        if(mm < m-1) mm++;
        else {
            mm = 0;
            if(hh < h-1) hh++;
            else hh = 0;
        }
    }
}

int main() {
    ios::sync_with_stdio(0), cin.tie(0);
    int T = 1;
    cin >> T;
    while(T--) {
        solve();
    }
    return 0;
}