#include <iostream>
#include <algorithm>
#include <utility>
#include <vector>
#include <unordered_map>

using namespace std;

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

bool            is_valid(int hour, int minute)
{
    int         a, b, c, d;
    unordered_map<int, int>::iterator it_a, it_b, it_c, it_d;

    a = hour / 10;
    b = hour % 10;
    c = minute / 10;
    d = minute % 10;
    if ((it_a = mp.find(a)) == mp.end() || (it_b = mp.find(b)) == mp.end() ||
        (it_c = mp.find(c)) == mp.end() || (it_d = mp.find(d)) == mp.end())
        return false;
    if (it_d->second * 10 + it_c->second >= h ||
        it_b->second * 10 + it_a->second >= m)
        return false;
    printf("%d%d:%d%d\n", a, b, c, d);
    return true;
}

void            solution()
{
    
    int         hour, minute;

    scanf("%d %d", &h, &m);
    scanf("%d:%d", &hour, &minute);
    while (!is_valid(hour, minute))
    {
        minute++;
        if (minute >= m)
        {
            minute = 0;
            hour++;
        }
        if (hour >= h)
            hour = 0;
    }
}

int             main(void)
{
    int         t;

    scanf("%d", &t);
    mp.insert({0, 0});
    mp.insert({1, 1});
    mp.insert({2, 5});
    mp.insert({5, 2});
    mp.insert({8, 8});
    while (t--)
    {
        solution();
    }
    return 0;
}