#pragma GCC optimize("Ofast")
#pragma GCC optimization("unroll-loops")
#pragma GCC target("avx,avx2,fma")
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define deb(x) cout << #x << " " << x << endl;
#define mod 1000000007
#define mod2 998244353
#define fast std::ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
#define endl "\n"
#define all(x) (x).begin(), (x).end()
#define rall(v) v.rbegin(), v.rend()

const ll INF = 1e18;
const ll NEGINF = -1 * INF;

ll gcd(ll a, ll b)
{
    if (b == 0)
    {
        return a;
    }
    return gcd(b, a % b);
}

ll my_pow(ll a, ll n, ll m = INF)
{
    ll res = 1;
    while (n)
    {
        if (n % 2)
        {
            res = (res * a) % m;
            n--;
        }
        a = (a * a) % m;
        n /= 2;
    }
    return res;
}

int h, m;
map<int, int> mp;

bool isValid(int H, int M)
{
    int h1 = H / 10;
    if (mp.find(h1) == mp.end())
    {
        return false;
    }
    int h2 = H % 10;
    if (mp.find(h2) == mp.end())
    {
        return false;
    }
    int m1 = M / 10;
    if (mp.find(m1) == mp.end())
    {
        return false;
    }
    int m2 = M % 10;
    if (mp.find(m2) == mp.end())
    {
        return false;
    }
    int newH1 = mp[m2];
    int newH2 = mp[m1];
    int newM1 = mp[h2];
    int newM2 = mp[h1];
    int newHr = newH1 * 10 + newH2;
    int newMin = newM1 * 10 + newM2;
    if (newHr < h && newMin < m)
    {
        return true;
    }
    else
    {
        return false;
    }
}

void solve()
{
    cin >> h >> m;
    string s;
    cin >> s;
    mp[0] = 0;
    mp[1] = 1;
    mp[2] = 5;
    mp[5] = 2;
    mp[8] = 8;
    int hr = (s[0] - '0') * 10 + (s[1] - '0');
    int min = (s[3] - '0') * 10 + (s[4] - '0');
    // deb(hr);
    // deb(min);
    while (true)
    {
        if (isValid(hr, min))
        {
            if (hr <= 9)
            {
                cout << 0;
            }
            cout << hr << ":";
            if (min <= 9)
            {
                cout << 0;
            }
            cout << min;
            cout << endl;
            return;
        }
        else
        {
            min++;
            if (min == m)
            {
                min = 0;
                hr++;
                if (hr == h)
                {
                    hr = 0;
                }
            }
        }
    }
}

int main()
{
    fast;
#ifndef ONLINE_JUDGE
    freopen("/home/kalit/Desktop/Data Structures-Algo-Competitive/src/codeforces/input.txt", "r", stdin);
    freopen("/home/kalit/Desktop/Data Structures-Algo-Competitive/src/codeforces/output.txt", "w", stdout);
#endif
    int T = 1;
    cin >> T;
    while (T--)
    {
        solve();
    }
    //cout<< "Done in " << clock() / CLOCKS_PER_SEC <<"sec"<< endl;
    return 0;
}