//Flower_On_Stone
#include <bits/stdc++.h>

using namespace std;

const int MIRROR[] = {0, 1, 5, -1, -1, 2, -1, -1, 8, -1};

int test, h, m;
string strClock;
int hour, minute;

int toInt(char ch) { return ch - '0'; }

string toString(int x)
{
    string resuft = "";
    for (int i = 1; i <= 2; i++)
    {
        resuft.push_back(char(x % 10 + '0'));
        x /= 10;
    }
    reverse(resuft.begin(), resuft.end());
    return resuft;
}

bool check(int hour, int minute)
{
    if (min({MIRROR[hour % 10], MIRROR[hour / 10], MIRROR[minute % 10], MIRROR[minute / 10]}) == -1)
    {
        return false;
    }
    return (MIRROR[minute % 10] * 10 + MIRROR[minute / 10] < h && MIRROR[hour % 10] * 10 + MIRROR[hour / 10] < m);
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
#ifdef Flower_On_Stone
    freopen("DEBUG.inp", "r", stdin);
    freopen("DEBUG.out", "w", stdout);
#endif // Flower_On_Stone
    cin >> test;
    while (test--)
    {
        cin >> h >> m;
        cin >> strClock;
        hour = toInt(strClock[0]) * 10 + toInt(strClock[1]);
        minute = toInt(strClock[3]) * 10 + toInt(strClock[4]);
        while (!check(hour, minute))
        {
            minute++;
            if (minute == m)
            {
                minute = 0;
                hour = (hour + 1) % h;
            }
        }
        cout << toString(hour) + ":" + toString(minute) << '\n';
    }

    return 0;
}