#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <tuple>
#include <deque>
#include <array>
#include <numeric>
#include <bitset>
#include <iomanip>
#include <cassert>
#include <chrono>
#include <random>
#include <limits>
#include <iterator>
#include <functional>
#include <sstream>
#include <fstream>
#include <complex>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
using namespace std;

using ll = long long;
constexpr int INF = 1001001001;
constexpr int mod = 1000000007;
// constexpr int mod = 998244353;

template<class T>
inline bool chmax(T& x, T y){
    if(x < y){
        x = y;
        return true;
    }
    return false;
}
template<class T>
inline bool chmin(T& x, T y){
    if(x > y){
        x = y;
        return true;
    }
    return false;
}

bool ok[10];
int convert[10];

void solve(){
    int h, m;
    string s;
    cin >> h >> m >> s;
    int H = stoi(s.substr(0, 2)), M = stoi(s.substr(3, 2));
    for(;;){
        bool flag = true;
        int H2 = 0, M2 = 0;
        int x = H;
        vector<int> a(2);
        int k = 0;
        while(x > 0){
            flag &= ok[x % 10];
            a[k++] = x % 10;
            x /= 10;
        }
        M2 = convert[a[0]] * 10 + convert[a[1]];
        flag &= (M2 < m);

        a[0] = a[1] = 0;
        x = M;
        k = 0;
        while(x > 0){
            flag &= ok[x % 10];
            a[k++] = x % 10;
            x /= 10;
        }
        H2 = convert[a[0]] * 10 + convert[a[1]];
        flag &= (H2 < h);

        if(flag){
            cout << setfill('0') << right << setw(2) << H << ':';
            cout << setfill('0') << right << setw(2) << M << '\n';
            return;
        }
        if(++M == m){
            M = 0;
            if(++H == h){
                H = 0;
            }
        }
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    ok[0] = true; 
    ok[1] = true; convert[1] = 1;
    ok[2] = true; convert[2] = 5;
    ok[5] = true; convert[5] = 2;
    ok[8] = true; convert[8] = 8;

    int T;
    cin >> T;
    while(T--)  solve();    

    return 0;
}