#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

const int N = 55;

int t;
int h, m;
char s[10];
int valid[110] = { 0,1,2,5,8,10,11,12,15,18,20,21,22,25,28,50,51,52,55,58,80,81,82,85,88,100};//25

int find(int x)
{
	int l = 0, r = 25;
	while (l < r)
	{
		int mid = l + r >> 1;
		if (valid[mid] >= x)
			r = mid;
		else
			l = mid + 1;
	}
	return l;
}

bool checknum(char c)
{
	int x = c - '0';
	if (x == 3 || x == 4 || x == 6 || x == 7 || x == 9)
		return false;
	return true;
}

int getreflect(int c)
{
	if (c == 0)
		return 0;
	if (c == 1)
		return 1;
	if (c == 2)
		return 5;
	if (c == 5)
		return 2;
	if (c == 8)
		return 8;
}

bool valck(int x, int mode)
{
	int k = valid[find(x)];
	if (k != x)
		return false;
	if (mode == 1 && k > h - 1)
		return false;
	if (mode == 2 && k > m - 1)
		return false;
	int temp = k / 10;
	temp = getreflect(temp);
	k = temp + getreflect(k % 10) * 10;
	if (mode == 1 && k > m - 1)
		return false;
	if (mode == 2 && k > h - 1)
		return false;
	return true;
}

bool check(char str[])
{
	if (!checknum(str[1]) || !checknum(str[2]) || !checknum(str[4]) || !checknum(str[5]))
		return false;
	if (10 * getreflect(str[5]) + getreflect(str[4]) > h - 1)
		return false;
	if (10 * getreflect(str[2]) + getreflect(str[1]) > m - 1)
		return false;
	return true;
}

int main()
{
	scanf("%d", &t);
	while (t--)
	{
		scanf("%d%d%s", &h, &m, s + 1);
		int hour = 10 * (s[1] - '0') + (s[2] - '0');
		int min = 10 * (s[4] - '0') + (s[5] - '0');
		if (valck(hour, 1) && valck(min, 2))
			puts(s + 1);
		else
		{
			if (valck(hour, 1))
			{
				while (1)
				{
					min = valid[find(min + 1)];
					if (min > m - 1)
					{
						while (1)
						{
							hour = valid[find(hour + 1)];
							if (hour > h - 1)
							{
								hour = 0;
								break;
							}
							if (valck(hour, 1))
								break;
						}
						min = 0;
						if (hour < 10)
							printf("0%d:00\n", hour);
						else
							printf("%d:00\n", hour);
						break;
					}
					if (valck(min, 2))
					{
						if (hour < 10)
							printf("0%d:", hour);
						else
							printf("%d:", hour);
						if (min < 10)
							printf("0%d\n", min);
						else
							printf("%d\n", min);
						break;
					}

				}
			}
			else
			{
				while (1)
				{
					hour = valid[find(hour + 1)];
					if (hour > h - 1)
					{
						hour = 0;
						break;
					}
					if (valck(hour, 1))
						break;
				}
				if (hour < 10)
					printf("0%d:00\n", hour);
				else
					printf("%d:00\n", hour);
			}
		}
	}
	//printf("%d %d\n", find(89),valid[find(89)]);
	return 0;
}