#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define INF 987654321
ll gcd(ll a, ll b) { for (; b; a %= b, swap(a, b)); return a; }
int h[3], m[3];
int H, M;
int chk[5] = { 3, 4, 6, 7, 9 };

bool Check(void)
{
    bool hasAns = true;
    for (int i = 0; i < 5; i++)
    {
        if (h[0] == chk[i] || h[1] == chk[i] || m[0] == chk[i] || m[1] == chk[i])
        {
            hasAns = false;
            break;
        }
    }
    int mm[2], hh[2];
    mm[1] = h[0], mm[0] = h[1], hh[1] = m[0], hh[0] = m[1];
    for (int i = 0; i < 2; i++)
    {
        if (mm[i] == 2 || mm[i] == 5)
            mm[i] = 7 - mm[i];
        if (hh[i] == 2 || hh[i] == 5)
            hh[i] = 7 - hh[i];
    }
    int Hour = hh[0] * 10 + hh[1];
    int Minute = mm[0] * 10 + mm[1];
    if (Hour >= H || Minute >= M) 
        hasAns = false;
    return hasAns;
}

void Move(void)
{
    m[1]++;
    if (m[1] > 9)
    {
        m[0]++;
        m[1] = 0;
    }
    int Minute = m[0] * 10 + m[1];
    if (Minute >= M)
    {
        h[1]++;
        m[0] = m[1] = 0;
    }
    if (h[1] > 9)
    {
        h[0]++;
        h[1] = 0;
    }
    int Hour = h[0] * 10 + h[1];
    if (Hour >= H)
    {
        h[0] = h[1] = m[0] = m[1] = 0;
    }
}

int main(void)
{
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    int t; cin >> t;
    while (t--)
    {
        cin >> H >> M;
        string st; cin >> st;
        h[0] = st[0] - '0', h[1] = st[1] - '0';
        m[0] = st[3] - '0', m[1] = st[4] - '0';
        while (true)
        {
            bool flag = Check();
            if (flag)
            {
                cout << h[0] << h[1] << ":" << m[0] << m[1] << "\n";
                break;
            }
            Move();
        }
    }
}