#include <bits/stdc++.h>
using namespace std;

bool t[10000];

void solve(void)
{
	int h, m, HH, MM, i, j, l;

	scanf("%d %d %d:%d", &h, &m, &HH, &MM);
	
	memset(t, false, sizeof(t));

	for (i = 0; i < h; i++)
		for (j = 0; j < m; j++)
		{
			string p = to_string(i / 10) + to_string(i % 10) + to_string(j / 10) + to_string(j % 10);
			bool bad = false;

			for (auto k : p)
				if (k != '0' && k != '1' && k != '2' && k != '5' && k != '8')
				{
					bad = true;
					break;
				}

			reverse(p.begin(), p.end());
			for (l = 0; l < 4; l++)
				if (p[l] == '2' || p[l] == '5')
					p[l] = '2' + '5' - p[l];

			if (stoi(p.substr(0, 2)) >= h || stoi(p.substr(2, 2)) >= m)
				bad = true;

			if (!bad)
				t[i * 100 + j] = true;
		}

	int cnt = 0;
	bool flag = false;
	int pos = -1;

	for (i = HH; i < h && !flag; i++)
		for (j = (i == HH ? MM : 0); j < m && !flag; j++)
		{
			cnt++;
			if (t[i * 100 + j])
			{
				pos = i * 100 + j;
				flag = true;
			}
		}
	for (i = 0; i < h && !flag; i++)
		for (j = 0; j < m && !flag; j++)
		{
			cnt++;
			if (t[i * 100 + j])
			{
				pos = i * 100 + j;
				flag = true;
			}
		}

	printf("%02d:%02d\n", pos / 100, pos % 100);
}

int main(void)
{
	int t;

	scanf("%d", &t);

	while (t--)
		solve();

	return 0;
}