The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts $h$ hours and each hour lasts $m$ minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from $0$ to $h-1$ and minutes are numbered from $0$ to $m-1$.

That's how the digits are displayed on the clock. Please note that digit $1$ is placed in the middle of its position.

A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day).

The image of the clocks in the mirror is reflected against a vertical axis.

The reflection is not a valid time.

The reflection is a valid time with $h=24$, $m = 60$. However, for example, if $h=10$, $m=60$, then the reflection is not a valid time.

An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment $s$ and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid.

It can be shown that with any $h$, $m$, $s$ such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest.

You are asked to solve the problem for several test cases.


-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 100$) — the number of test cases.

The next $2 \cdot T$ lines contain the description of test cases. The description of each test case consists of two lines.

The first line of a test case contains two integers $h$, $m$ ($1 \le h, m \le 100$).

The second line contains the start time $s$ in the described format HH:MM.


-----Output-----

For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct.


-----Examples-----

Input
5
24 60
12:21
24 60
23:59
90 80
52:26
1 100
00:01
10 10
04:04
Output
12:21
00:00
52:28
00:00
00:00


-----Note-----

In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct.

Source: codeforces | Difficulty: EASY
Tags: Implementation

Complete search


Solutions:
import math
ref = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}

def isValid(hr, minu, h, m):
	invalid = {'3', '4', '6', '7', '9'}
	for ch in hr:
		if ch in invalid:
			return False
	for ch in minu:
		if ch in invalid:
			return False
	(refH, refM) = ('', '')
	for ch in hr:
		refH = ref[ch] + refH
	for ch in minu:
		refM = ref[ch] + refM
	if int(refM) >= h or int(hr) >= h or int(refH) >= m or (int(minu) >= m):
		return False
	if int(refM) * m + int(refH) > h * m + m:
		return False
	return True
for test in range(int(input())):
	(h, m) = map(int, input().split())
	(hrs, minu) = map(str, input().split(':'))
	while not isValid(hrs, minu, h, m):
		temp = int(minu) + 1
		minu = str(temp)
		if int(minu) >= m:
			t1 = int(hrs) + 1
			hrs = str(t1)
			minu = '00'
		if int(hrs) >= h:
			hrs = '00'
			minu = '00'
		if len(hrs) == 1:
			hrs = '0' + hrs
		if len(minu) == 1:
			minu = '0' + minu
	print(hrs + ':' + minu)


N = 100
a = (0, 1, 5, N, N, 2, N, N, 8, N)

def g(s):
	(u, v, x, y) = (a[int(x)] for x in s if ':' > x)
	return h > x + y * 10 and v * 10 + u < m
R = lambda x=' ': map(int, input().split(x))
(t,) = R()
while t:
	t -= 1
	(h, m) = R()
	(x, y) = R(':')
	y += x * m
	print(next(filter(g, (f'{i // m % h:02}:{i % m:02}' for i in range(y, y + h * m)))))


def isCorrect(_h, _m, h, m):
	(shh, smm) = (str(_h), str(_m))
	if _h < 10:
		shh = '0' + shh
	if _m < 10:
		smm = '0' + smm
	s = f'{shh}:{smm}'
	if '3' in s or '4' in s or '6' in s or ('7' in s) or ('9' in s):
		return False
	if _h >= h or _h < 0:
		return False
	if _m >= m or _m < 0:
		return False
	sRevH = list(smm[::-1])
	if sRevH[0] == '2':
		sRevH[0] = '5'
	elif sRevH[0] == '5':
		sRevH[0] = '2'
	if sRevH[1] == '2':
		sRevH[1] = '5'
	elif sRevH[1] == '5':
		sRevH[1] = '2'
	revH = int(''.join(sRevH))
	if revH >= h or revH < 0:
		return False
	sRevM = list(shh[::-1])
	if sRevM[0] == '2':
		sRevM[0] = '5'
	elif sRevM[0] == '5':
		sRevM[0] = '2'
	if sRevM[1] == '2':
		sRevM[1] = '5'
	elif sRevM[1] == '5':
		sRevM[1] = '2'
	revM = int(''.join(sRevM))
	if revM >= m or revM < 0:
		return False
	return s

def nextS(s, _h, _m, h, m):
	newM = _m
	newH = _h
	while 1:
		res = isCorrect(newH, newM, h, m)
		if res:
			return res
		newM += 1
		if newM >= m:
			newM = 0
			newH += 1
			if newH >= h:
				newH = 0
t = int(input())
while t > 0:
	(h, m) = list(map(int, input().split()))
	s = input()
	(_h, _m) = list(map(int, s.split(':')))
	print(nextS(s, _h, _m, h, m))
	t -= 1


def refPos(twodigitstr):
	se = {'1': '1', '0': '0', '8': '8', '2': '5', '5': '2'}
	(a, b) = (twodigitstr[0], twodigitstr[1])
	if a in se and b in se:
		return ''.join([se[b], se[a]])
	return False
for _ in range(int(input())):
	(H, M) = map(int, input().split())
	s = input()
	ans = refPos(s[:2])
	flag = False
	if ans:
		if int(ans) < M:
			for m in range(int(s[3:]), M):
				strM = '0' * (2 - len(str(m))) + str(m)
				ans1 = refPos(strM)
				if ans1:
					if int(ans1) < H:
						flag = True
						print(s[:3] + strM)
						break
	if not flag:
		for h in range(int(s[:2]) + 1, H):
			strH = '0' * (2 - len(str(h))) + str(h)
			ans = refPos(strH)
			if ans:
				if int(ans) < M:
					flag = True
					print(strH + ':' + '00')
					break
	if not flag:
		print('00:00')


import io
import os
from collections import Counter, defaultdict, deque
reflect = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
valid = {}
for h1 in [0, 1, 2, 5, 8]:
	for h2 in [0, 1, 2, 5, 8]:
		h = h1 * 10 + h2
		flip = reflect[h2] * 10 + reflect[h1]
		valid[h] = flip

def makeClock(h, m):
	return str(h).zfill(2) + ':' + str(m).zfill(2)

def solve(H, M, S):
	(x, y) = map(int, S.split(':'))
	while True:
		if x in valid and y in valid:
			h = valid[y]
			m = valid[x]
			if 0 <= h < H and 0 <= m < M:
				return makeClock(x, y)
		y += 1
		if y == M:
			y = 0
			x += 1
			if x == H:
				x = 0
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
	(H, M) = [int(x) for x in input().split()]
	S = input().decode().rstrip()
	ans = solve(H, M, S)
	print(ans)


use_digits = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}

def is_useful(num, less_than):
	x = num % 10
	y = num // 10
	if x in use_digits and y in use_digits:
		x = use_digits[x]
		y = use_digits[y]
		new_num = x * 10 + y
		return new_num < less_than
	else:
		return False
	return x in use_digits and y in use_digits

def find_next_time(case):
	(h, m, ih, im) = case
	total_in_min = h * m
	curr_in_min = ih * m + im
	while curr_in_min < total_in_min:
		curr_h = curr_in_min // m
		curr_m = curr_in_min % m
		if is_useful(curr_h, m) and is_useful(curr_m, h):
			return (curr_h, curr_m)
		curr_in_min += 1
	return (0, 0)
test_cases = int(input())
cases = []
for _ in range(test_cases):
	(h, m) = map(int, input().split())
	(ih, im) = map(int, input().split(':'))
	cases.append([h, m, ih, im])
for case in cases:
	(h, m) = find_next_time(case)
	print('{:02d}:{:02d}'.format(h, m))


import sys, math
ref = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}

def is_valid(H, M, h, m):
	return h < H and m < M

def str_to_num(hs, ms, H, M):
	return int(hs) * M + int(ms)

def num_to_str(n, H, M):
	h = n // M % H
	m = n % M
	hs = '0' + str(h) if h < 10 else str(h)
	ms = '0' + str(m) if m < 10 else str(m)
	return (hs, ms)

def reflect(hs, ms):
	try:
		rms = ref[hs[1]] + ref[hs[0]]
		rhs = ref[ms[1]] + ref[ms[0]]
		return (rhs, rms)
	except KeyError:
		return (None, None)

def main(pname):
	t = int(input())
	for j in range(t):
		(H, M) = [int(i) for i in input().split()]
		(hs, ms) = input().split(':')
		n0 = str_to_num(hs, ms, H, M)
		for i in range(n0, n0 + H * M):
			(nhs, nms) = num_to_str(i, H, M)
			(rhs, rms) = reflect(nhs, nms)
			if rhs is not None and is_valid(H, M, int(rhs), int(rms)):
				print(nhs + ':' + nms)
				break
main('prob2')


N = 100
a = (5, N, N, 2, N, N, 8, N, 0, 1) * 6
R = lambda x=' ': map(int, input().split(x))
(t,) = R()
while t:
	t -= 1
	(h, m) = R()
	(x, y) = R(':')
	y += x * m
	u = v = w = q = N
	while h <= w + q * 10 or v * 10 + u >= m:
		r = f'{y // m % h:02}:{y % m:02}'
		y += 1
		(u, v, _, w, q) = (a[ord(x)] for x in r)
	print(r)


mirror = [0, 1, 5, 100, 100, 2, 100, 100, 8, 100]

def print_ans(hours, minutes):
	ans = str(hours).zfill(2) + ':' + str(minutes).zfill(2)
	print(ans)
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	(sh, sm) = map(int, input().split(':'))
	while True:
		mirror_h = mirror[sm % 10] * 10 + mirror[sm // 10]
		mirror_m = mirror[sh % 10] * 10 + mirror[sh // 10]
		if mirror_h < h and mirror_m < m:
			print_ans(sh, sm)
			break
		sm += 1
		if sm == m:
			sm = 0
			sh = (sh + 1) % h


mp = {1: 1, 2: 5, 5: 2, 8: 8, 0: 0}

def getreflect(mh, lh, mm, lm, h, m):
	boo = True
	global mp
	if lh not in mp.keys():
		return False
	if mh not in mp.keys():
		return False
	if lm not in mp.keys():
		return False
	if mm not in mp.keys():
		return False
	if mp[lh] * 10 + mp[mh] >= m or mp[lm] * 10 + mp[mm] >= h:
		return False
	return boo
t = int(input())
while t:
	t -= 1
	(n, k) = input().split()
	time = input()
	(h, m) = (int(n), int(k))
	(mh, lh, mm, lm) = (int(time[0]), int(time[1]), int(time[3]), int(time[4]))
	while True:
		if mm * 10 + lm >= m:
			mm = 0
			lm = 0
			lh += 1
			if lh >= 10:
				lh = 0
				mh += 1
		if mh * 10 + lh >= h:
			lh = 0
			mh = 0
		if getreflect(mh, lh, mm, lm, h, m):
			ans = str(mh) + str(lh) + ':' + str(mm) + str(lm)
			break
		lm += 1
		if lm >= 10:
			lm = 0
			mm += 1
	print(ans)


import sys
import os
handler = open('input') if 'HOME' in os.environ else sys.stdin
T = int(handler.readline())

def repeat(func):
	for _ in range(T):
		func()

@repeat
def solve():
	(h, m) = map(int, handler.readline().split())
	(a, b) = map(int, handler.readline().strip().split(':'))
	d = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8', ':': ':'}

	def check(a, b):
		n = ''
		for x in reversed(f'{a:02}:{b:02}'):
			if x not in d:
				return False
			else:
				n += d[x]
		(a, b) = map(int, n.split(':'))
		return a < h and b < m
	while True:
		if check(a, b):
			print(f'{a:02}:{b:02}')
			return
		if b < m - 1:
			b += 1
		elif a < h - 1:
			a += 1
			b = 0
		else:
			(a, b) = (0, 0)


symmetric_digits = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}

def invert_digits(tt):
	res = ''
	for d in reversed(f'{tt:02d}'):
		if d not in symmetric_digits:
			return float('inf')
		res += symmetric_digits[d]
	return int(res)

def valid(hh, mm, h, m):
	return invert_digits(hh) < m and invert_digits(mm) < h
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	(sh, sm) = map(int, input().split(':'))
	while True:
		if valid(sh, sm, h, m):
			print(f'{sh:02d}:{sm:02d}')
			break
		sm += 1
		sh += sm // m
		sm %= m
		sh %= h


def mirror(h, m):
	sh = list(str(h).zfill(2))
	sm = list(str(m).zfill(2))
	if set(['3', '4', '6', '7', '9']) & set(sh + sm):
		return False
	m = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}
	return (int(m[sm[1]] + m[sm[0]]), int(m[sh[1]] + m[sh[0]]))

def tick(h, m, H, M):
	m += 1
	if m == M:
		m = 0
		h += 1
		if h == H:
			h = 0
	return (h, m)

def solve():
	(H, M) = map(int, input().split())
	(h, m) = map(int, input().split(':'))
	while True:
		r = mirror(h, m)
		if r:
			(mh, mm) = r
			if mh < H and mm < M:
				print(str(h).zfill(2) + ':' + str(m).zfill(2))
				break
		(h, m) = tick(h, m, H, M)
t = int(input())
while t > 0:
	solve()
	t -= 1


T = int(input())
ans = [0] * T
for t in range(T):
	(h, m) = map(int, input().split())
	(hh, mm) = input().split(':')
	mi = [0, 1, 5, 100, 100, 2, 100, 100, 8, 100]
	for i in range(int(mm), m):
		if i < 10:
			new_h = mi[i] * 10
		else:
			new_h = mi[int(str(i)[1])] * 10 + mi[int(str(i)[0])]
		new_m = mi[int(hh[1])] * 10 + mi[int(hh[0])]
		if new_h < h and new_m < m:
			if i < 10:
				ans[t] = hh + ':0' + str(i)
			else:
				ans[t] = hh + ':' + str(i)
			break
	else:
		for i in range(int(hh) + 1, h):
			if i < 10:
				new_m = mi[i] * 10
			else:
				new_m = mi[int(str(i)[1])] * 10 + mi[int(str(i)[0])]
			if new_m < m:
				if i < 10:
					ans[t] = '0' + str(i) + ':00'
				else:
					ans[t] = str(i) + ':00'
				break
		else:
			ans[t] = '00:00'
print(*ans, sep='\n')


import sys
input = sys.stdin.readline
from collections import defaultdict as dc
from collections import Counter
from bisect import bisect_right, bisect_left
import math
from operator import itemgetter
from heapq import heapify, heappop, heappush
from queue import PriorityQueue as pq
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	s = list(input()[:-1].split(':'))
	(a, b) = (int(s[0]), int(s[1]))
	(w, x, y, z) = (int(s[0][0]), int(s[0][1]), int(s[1][0]), int(s[1][1]))
	flag = 0
	if w in [2, 5, 0, 1, 8] and x in [2, 5, 1, 0, 8] and (y in [2, 5, 1, 0, 8]) and (z in [2, 5, 1, 0, 8]):
		if w == 2:
			w = 5
		elif w == 5:
			w = 2
		if x == 2:
			x = 5
		elif x == 5:
			x = 2
		if y == 2:
			y = 5
		elif y == 5:
			y = 2
		if z == 2:
			z = 5
		elif z == 5:
			z = 2
		(e, f) = (10 * z + y, 10 * x + w)
		flag = 1
	if flag == 1 and e >= 0 and (e < h) and (f >= 0) and (f < m):
		print(str(s[0]) + ':' + str(s[1]))
		flag = 0
	else:
		(p, q) = (int(s[0]), int(s[1]))
		q = (q + 1) % m
		if q == 0:
			p = (p + 1) % h
		(c1, c2) = (0, 0)
		(t1, t2) = (p, q)
		while t1 > 0:
			t1 = t1 // 10
			c1 += 1
		while t2 > 0:
			t2 = t2 // 10
			c2 += 1
		if c1 == 2:
			r = str(p)
			(w, x) = (int(r[0]), int(r[1]))
		else:
			w = 0
			x = p
		if c2 == 2:
			r = str(q)
			(y, z) = (int(r[0]), int(r[1]))
		else:
			y = 0
			z = q
		while s[0] + ':' + s[1] != str(w) + str(x) + ':' + str(y) + str(z):
			(c1, c2) = (0, 0)
			(t1, t2) = (p, q)
			while t1 > 0:
				t1 = t1 // 10
				c1 += 1
			while t2 > 0:
				t2 = t2 // 10
				c2 += 1
			if c1 == 2:
				r = str(p)
				(w, x) = (int(r[0]), int(r[1]))
			else:
				w = 0
				x = p
			if c2 == 2:
				r = str(q)
				(y, z) = (int(r[0]), int(r[1]))
			else:
				y = 0
				z = q
			(ab, bc, cd, da) = (w, x, y, z)
			if w in [2, 5, 0, 1, 8] and x in [2, 5, 1, 0, 8] and (y in [2, 5, 1, 0, 8]) and (z in [2, 5, 1, 0, 8]):
				if w == 2:
					ab = 5
				elif w == 5:
					ab = 2
				if x == 2:
					bc = 5
				elif x == 5:
					bc = 2
				if y == 2:
					cd = 5
				elif y == 5:
					cd = 2
				if z == 2:
					da = 5
				elif z == 5:
					da = 2
				(e, f) = (10 * da + cd, 10 * bc + ab)
				if e >= 0 and e < h and (f >= 0) and (f < m):
					break
			q = (q + 1) % m
			if q == 0:
				p = (p + 1) % h
		print(str(w) + str(x) + ':' + str(y) + str(z))


change = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
bad = (3, 4, 6, 7, 9)
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	s = input()
	ch = int(s[:2])
	cm = int(s[3:])
	while True:
		if not (ch % 10 in bad or cm % 10 in bad or ch // 10 in bad or (cm // 10 in bad)):
			chm = change[ch % 10] * 10 + change[ch // 10]
			chh = change[cm % 10] * 10 + change[cm // 10]
			if chh < h and chm < m:
				if ch < 10:
					print('0', end='')
				print(ch, end=':')
				if cm < 10:
					print('0', end='')
				print(cm)
				break
		cm += 1
		if cm == m:
			cm = 0
			ch += 1
			if ch == h:
				print('00:00')
				break


for i in range(int(input())):
	(h, m) = map(int, input().split())
	time = str(input())
	(hour, minute) = (int(time[0:2]), int(time[3:]))
	stting = False
	per = [0, 1, 2, 5, 8]
	dic = {'0': 0, '1': 1, '2': 5, '5': 2, '8': 8}
	while stting == False:
		if int(time[0:2]) % 10 in per and int(int(time[0:2]) / 10) % 10 in per and (int(time[3:]) % 10 in per) and (int(int(time[3:]) / 10) % 10 in per) and (dic[str(int(time[3:]) % 10)] * 10 + dic[str(int(int(time[3:]) / 10) % 10)] < h) and (dic[str(int(time[0:2]) % 10)] * 10 + dic[str(int(int(time[0:2]) / 10) % 10)] < m):
			print(time)
			stting = True
		elif int(time[3:]) < m - 1 and int(time[3:]) > 8:
			time = time[0:2] + ':' + str(int(time[3:]) + 1)
		elif int(time[3:]) < m - 1 and int(time[3:]) < 9:
			time = time[0:2] + ':0' + str(int(time[3:]) + 1)
		elif int(time[3:]) == m - 1 and int(time[0:2]) < h - 1 and (int(time[0:2]) > 8):
			time = str(int(time[0:2]) + 1) + ':00'
		elif int(time[3:]) == m - 1 and int(time[0:2]) < h - 1 and (int(time[0:2]) < 9):
			time = '0' + str(int(time[0:2]) + 1) + ':00'
		else:
			time = '00:00'


import time, math as mt, bisect as bs, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
from collections import defaultdict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count
mx = 10 ** 7
spf = [mx] * (mx + 1)

def readTree(n, e):
	adj = [set() for i in range(n + 1)]
	for i in range(e):
		(u1, u2) = IP()
		adj[u1].add(u2)
	return adj

def sieve():
	li = [True] * (10 ** 3 + 5)
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	(prime, cur) = ([0] * 200, 0)
	for i in range(10 ** 3 + 5):
		if li[i] == True:
			prime[cur] = i
			cur += 1
	return prime

def SPF():
	mx = 10 ** 6 + 1
	spf[1] = 1
	for i in range(2, mx):
		if spf[i] == 1000000000.0:
			spf[i] = i
			for j in range(i * i, mx, i):
				if i < spf[j]:
					spf[j] = i
	return

def prime(n, d):
	prm = set()
	while n != 1:
		prm.add(spf[n])
		n = n // spf[n]
	for ele in prm:
		d[ele] = d.get(ele, 0) + 1
	return
mod = 10 ** 9 + 7
inf = 10000000000000000

def check(s):
	stack = []
	for ele in s:
		if ele == ')' and (not stack):
			return 0
		elif ele == ')':
			stack.pop()
		if ele == '(':
			stack.append('(')
	if stack:
		return 0
	return 1

def getans(h, m):
	if len(h) == 1:
		h = '0' + h
	if len(m) == 1:
		m = '0' + m
	ans = h + ':' + m
	return (ans, h, m)

def check(h, m):
	for ele in h:
		if ele not in '01258':
			return False
	for ele in m:
		if ele not in '01258':
			return False
	return True

def check2(hh, mm, h, m):
	hh = hh[::-1]
	mm = mm[::-1]
	(newh, newm) = ('', '')
	for ele in mm:
		if ele == '2':
			newh += '5'
		elif ele == '5':
			newh += '2'
		else:
			newh += ele
	for ele in hh:
		if ele == '2':
			newm += '5'
		elif ele == '5':
			newm += '2'
		else:
			newm += ele
	(newh, newm) = (int(newh), int(newm))
	if newh >= 0 and newh < h and (newm >= 0) and (newm < m):
		return True
	return False

def solve():
	(h, m) = IP()
	s = stdin.readline()
	hh = int(s[:2])
	mm = int(s[3:5])
	while True:
		if check(str(hh), str(mm)):
			(ans, rh, rm) = getans(str(hh), str(mm))
			if check2(str(rh), str(rm), h, m):
				print(ans)
				return
		if mm == m - 1:
			mm = 0
			if hh == h - 1:
				hh = 0
			else:
				hh += 1
		else:
			mm += 1
	return
t = II()
for i in range(t):
	solve()


mirror = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}

def digits(v):
	return (v // 10, v % 10)
for _ in range(int(input())):
	(h, m) = list(map(int, input().split()))
	(sh, sm) = list(map(int, input().split(':')))
	while True:
		(sm2, sm1) = digits(sm)
		(sh2, sh1) = digits(sh)
		if sm1 in mirror and sm2 in mirror and (sh1 in mirror) and (sh2 in mirror):
			mh = mirror[sm1] * 10 + mirror[sm2]
			mm = mirror[sh1] * 10 + mirror[sh2]
			if mh < h and mm < m:
				print(str(sh2) + str(sh1) + ':' + str(sm2) + str(sm1))
				break
		sm += 1
		if sm == m:
			sm = 0
			sh += 1
			if sh == h:
				sh = 0


t = int(input())
while t:
	t -= 1
	(HR, MIN) = map(int, input().split())
	(h, m) = map(str, input().split(':'))
	static = ['0', '1', '5', '-1', '-1', '2', '-1', '-1', '8', '-1']
	while True:
		if int(m) >= MIN:
			h = str(int(h) + 1)
			if len(h) == 1:
				h = '0' + h
			m = '00'
		if int(h) >= HR:
			h = '00'
			m = '00'
		if static[int(m[1])] == '-1' or static[int(m[0])] == '-1' or static[int(h[1])] == '-1' or (static[int(h[0])] == '-1'):
			g = 1
		else:
			ih = static[int(m[1])] + static[int(m[0])]
			im = static[int(h[1])] + static[int(h[0])]
			if int(ih) < HR and int(im) < MIN:
				print(h, ':', m, sep='')
				break
		m = str(int(m) + 1)
		if len(m) == 1:
			m = '0' + m


correct = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
for i in range(int(input())):
	(h, m) = map(int, input().split())
	(oclock, minute) = map(int, input().split(':'))
	while True:
		(a, b) = (oclock // 10, oclock % 10)
		(c, d) = (minute // 10, minute % 10)
		try:
			new_oclock = int(str(correct[d]) + str(correct[c]))
			new_minute = int(str(correct[b]) + str(correct[a]))
			if new_oclock < h and new_minute < m:
				break
		except KeyError:
			pass
		minute += 1
		if minute == m:
			minute = 0
			oclock += 1
			oclock %= h
	(oclock, minute) = (str(oclock), str(minute))
	if len(oclock) == 1:
		oclock = '0' + oclock
	if len(minute) == 1:
		minute = '0' + minute
	print(oclock, ':', minute, sep='')


mirror = [0, 1, 5, 0, 0, 2, 0, 0, 8, 0]
arr = [1, 1, 1, 0, 0, 1, 0, 0, 1, 0]
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	s = input().split(':')
	(x, y) = map(int, s)
	while True:
		(a, b, c, d) = (*divmod(x, 10), *divmod(y, 10))
		if arr[a] and arr[b] and arr[c] and arr[d]:
			(a1, b1, c1, d1) = [mirror[i] for i in (a, b, c, d)]
			xr = d1 * 10 + c1
			yr = b1 * 10 + a1
			if xr < h and yr < m:
				print(str(x).zfill(2) + ':' + str(y).zfill(2))
				break
		y += 1
		if y == m:
			(x, y) = ((x + 1) % h, 0)


def changeNum(s, startDay, endDay, h, m):
	if s == endDay:
		s = startDay
		return s
	list1 = list(s)
	x = int(s[2:4])
	x += 1
	nextHr = False
	if x == m:
		x = 0
		nextHr = True
	if x < 10:
		list1[2] = '0'
		list1[3] = str(x)
	else:
		temp = str(x)
		list1[2] = temp[0]
		list1[3] = temp[1]
	if nextHr:
		x = int(s[0:2])
		x += 1
		if x == h:
			x = 0
		if x < 10:
			list1[0] = '0'
			list1[1] = str(x)
		else:
			temp = str(x)
			list1[0] = temp[0]
			list1[1] = temp[1]
	newS = ''
	for i in list1:
		newS += i
	return newS
ref = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8', ':': ':'}
tc = int(input())
for i in range(tc):
	(h, m) = map(int, input().split())
	startDay = '0000'
	endDay = ''
	if h <= 10:
		endDay += '0' + str(h - 1)
	else:
		endDay += str(h - 1)
	if m <= 10:
		endDay += '0' + str(m - 1)
	else:
		endDay += str(m - 1)
	s = input()
	s = s[0:2] + s[3:5]
	while True:
		allDigRef = True
		stemp = ''
		for digit in s:
			if digit not in ref:
				allDigRef = False
				break
			else:
				stemp += ref[digit]
		stemp = stemp[::-1]
		if not allDigRef:
			s = changeNum(s, startDay, endDay, h, m)
		else:
			validity = False
			if stemp[0:2] <= endDay[0:2] and stemp[2:4] <= endDay[2:4]:
				validity = True
			if validity:
				break
			else:
				s = changeNum(s, startDay, endDay, h, m)
	s = s[0:2] + ':' + s[2:4]
	print(s)


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inara():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
reflect = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]

def change(val):
	if val == 0:
		return 0
	digit = []
	sz = len(str(val))
	while val > 0:
		digit.append(val % 10)
		val //= 10
	for i in range(len(digit)):
		digit[i] = reflect[digit[i]]
		if digit[i] == -1:
			return -1
	ans = 0
	for d in digit:
		ans *= 10
		ans += d
	if len(digit) == 1:
		ans *= 10
	return ans

def good(s, h, m):
	hour = s // m
	hour %= h
	minute = s % m
	refHour = change(minute)
	refMinute = change(hour)
	if refHour == -1 or refMinute == -1:
		return False
	return refHour >= 0 and refHour < h and (refMinute >= 0) and (refMinute < m)
t = inp()
for _ in range(t):
	(h, m) = invr()
	(hour, minute) = map(int, input().split(':'))
	s = hour * m + minute
	while not good(s, h, m):
		s += 1
		s %= h * m
	hour = s // m
	minute = s % m
	hour %= h
	print('{:02d}:{:02d}'.format(hour, minute))


def valid(h, m, t):
	for i in t:
		for k in i:
			if d[int(j)] != None:
				temp += str(d[int(j)])
			else:
				return False

def isvalid(h, m, t):
	temp = ''
	for i in t:
		for j in i:
			if dict[int(j)] != None:
				temp += str(dict[int(j)])
			else:
				return False
	if int(temp[2:][::-1]) < h and int(temp[:2][::-1]) < m:
		return temp[:2] + ':' + temp[2:]
	return False
dict = {0: 0, 1: 1, 2: 5, 3: None, 4: None, 5: 2, 6: None, 7: None, 8: 8, 9: None}
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	t = input().split(':')
	while True:
		check = isvalid(h, m, t)
		if check:
			print(t[0] + ':' + t[1])
			break
		b = int(t[1]) + 1
		if b == m:
			d = int(t[0]) + 1
			if d == h:
				d = '00'
			b = '00'
		else:
			d = t[0]
		if int(b) <= 9:
			b = '0' + str(int(b))
		if int(d) <= 9:
			d = '0' + str(int(d))
		t = [str(d), str(b)]


import math
for _ in range(int(input())):
	(h, m) = list(map(int, input().split()))
	(h1, m1) = list(map(int, input().split(':')))
	dic = {1: 1, 2: 5, 5: 2, 8: 8, 0: 0}
	dd = list(dic.keys())
	i = h1
	j = m1
	while True:
		a1 = i % 10
		a2 = math.floor(i / 10)
		a3 = j % 10
		a4 = math.floor(j / 10)
		if a1 in dic.keys() and a2 in dic.keys() and (a3 in dic.keys()) and (a4 in dic.keys()):
			mm1 = dic[a1] * 10 + dic[a2]
			hh1 = dic[a3] * 10 + dic[a4]
			if mm1 < m and hh1 < h:
				mm1 = j
				hh1 = i
				if mm1 <= 9:
					mm1 = '0' + str(mm1)
				if hh1 < 10:
					hh1 = '0' + str(hh1)
				print(str(hh1) + ':' + str(mm1))
				break
			else:
				j += 1
				j = j % m
				if j == 0:
					i += 1
					i = i % h
					if i == h1 and j == m1:
						break
		else:
			j += 1
			j = j % m
			if j == 0:
				i += 1
				i = i % h
				if i == h1 and j == m1:
					break


def next_min(h, m, time):
	hh = time[0]
	mm = time[1] + 1
	if mm == m:
		mm = 0
		hh += 1
		if hh == h:
			hh = 0
	return [hh, mm]

def mirror(time):
	hh = time[0]
	mm = time[1]
	h1 = hh // 10
	h2 = hh % 10
	m1 = mm // 10
	m2 = mm % 10
	s = {0, 1, 2, 5, 8}
	if not (h1 in s and h2 in s and (m1 in s) and (m2 in s)):
		return [-1, -1]
	nh1 = reverse(m2)
	nh2 = reverse(m1)
	nm1 = reverse(h2)
	nm2 = reverse(h1)
	return [nh1 * 10 + nh2, nm1 * 10 + nm2]

def reverse(d):
	if d == 1:
		return 1
	if d == 2:
		return 5
	if d == 5:
		return 2
	if d == 8:
		return 8
	return 0
for i in range(int(input())):
	(h, m) = map(int, input().split())
	time = list(map(int, input().split(':')))
	mtime = mirror(time)
	while mtime[0] < 0 or mtime[0] >= h or mtime[1] >= m:
		time = next_min(h, m, time)
		mtime = mirror(time)
	hh = time[0]
	mm = time[1]
	h1 = hh // 10
	h2 = hh % 10
	m1 = mm // 10
	m2 = mm % 10
	print('{}{}:{}{}'.format(h1, h2, m1, m2))


def is_correct(h, m, h2, m2):
	mirror = {0: 0, 1: 10, 2: 50, 5: 20, 8: 80, 10: 1, 11: 11, 12: 51, 15: 21, 18: 81, 20: 5, 21: 15, 22: 55, 25: 25, 28: 85, 50: 2, 51: 12, 52: 52, 55: 22, 58: 82, 80: 8, 81: 18, 82: 58, 85: 28, 88: 88}
	if mirror.get(h2) != None and mirror.get(m2) != None:
		if mirror.get(h2) < m and mirror.get(m2) < h:
			return True
	return False
for i in range(int(input())):
	(h, m) = map(int, input().split())
	(h2, m2) = map(int, input().split(':'))
	while True:
		if is_correct(h, m, h2, m2):
			break
		m2 += 1
		if m2 >= m:
			m2 = 0
			h2 += 1
			if h2 >= h:
				h2 = 0
	print(':'.join([str(h2) if h2 > 9 else '0' + str(h2), str(m2) if m2 > 9 else '0' + str(m2)]))


clock = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
mirror = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]

def check(h1, h2, m1, m2, m, H, M):
	if m[h1] == -1 or m[h2] == -1 or m[m1] == -1 or (m[m2] == -1):
		return False
	if m[m2] * 10 + m[m1] < H and m[h2] * 10 + m[h1] < M:
		return True
	return False
q = int(input())
while q:
	(h, m) = input().split()
	(h, m) = (int(h), int(m))
	s = input()
	(h1, h2, m1, m2) = (int(s[0]), int(s[1]), int(s[3]), int(s[4]))
	while True:
		if check(h1, h2, m1, m2, mirror, h, m):
			print(str(h1) + str(h2) + ':' + str(m1) + str(m2))
			break
		else:
			m2 += 1
			if m2 == 10:
				m2 = 0
				m1 += 1
			if m1 * 10 + m2 >= m:
				m1 = 0
				m2 = 0
				h2 += 1
			if h2 == 10:
				h2 = 0
				h1 += 1
			if h1 * 10 + h2 >= h:
				h1 = 0
				h2 = 0
	q -= 1


from sys import stdin
from collections import Counter
from math import sqrt, factorial, log10, log, floor, ceil
from itertools import permutations, combinations, combinations_with_replacement
input = stdin.readline

def li():
	return list(map(int, input().split()))

def lis():
	return list(map(str, input().split()))

def mp():
	return map(int, input().split())

def inp():
	return int(input())

def inps():
	return str(input().strip())

def pr(n):
	return stdout.write(str(n) + '\n')
INF = float('inf')
reflect = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]

def change(s):
	if s == 0:
		return 0
	dig = []
	while s > 0:
		dig.append(s % 10)
		s //= 10
	for i in range(len(dig)):
		dig[i] = reflect[dig[i]]
		if dig[i] == -1:
			return -1
	res = 0
	for d in dig:
		res *= 10
		res += d
	if len(dig) == 1:
		res *= 10
	return res

def ok(s, h, m):
	hour = s // m
	hour %= h
	minute = s % m
	rh = change(minute)
	rm = change(hour)
	if rh == -1 or rm == -1:
		return False
	return rh >= 0 and rh < h and (rm >= 0) and (rm < m)

def solve():
	(h, m) = mp()
	(hour, minute) = map(int, input().split(':'))
	s = hour * m + minute
	while not ok(s, h, m):
		s += 1
		s %= h * m
	hour = s // m
	minute = s % m
	hour %= h
	print('{:02d}:{:02d}'.format(hour, minute))
t = inp()
for i in range(t):
	solve()


import sys, os, io
for _ in range(int(input())):
	(h, m) = [int(i) for i in input().split()]
	(a, b) = [int(i) for i in input().split(':')]
	x = '00'
	valid = [0, 1, 2, 5, 8]
	s = set()
	dic = {}
	for i in range(10):
		dic[str(i)] = str(i)
	dic['2'] = '5'
	dic['5'] = '2'
	for i in valid:
		for j in valid:
			s.add(str(i) + str(j))
	if a < 10:
		sa = '0' + str(a)
	else:
		sa = str(a)
	if sa in s:
		for j in range(b, 10 ** 5):
			i = j % m
			if b != 0 and i == 0:
				a += 1
			si = str(i)
			if i < 10:
				si = '0' + si
			ni = si[::-1]
			nni = ''
			for i in ni:
				nni += dic[i]
			ii = int(nni)
			if ii >= h:
				continue
			if si in s:
				x = si
				break
	y = a
	for j in range(a, 10 ** 5):
		i = j % h
		si = str(i)
		if i < 10:
			si = '0' + si
		ni = si[::-1]
		nni = ''
		for i in ni:
			nni += dic[i]
		ii = int(nni)
		if ii >= m:
			continue
		if si in s:
			y = si
			break
	if y != sa:
		x = '00'
	print(y + ':' + x)


t = int(input())
mirror = {0: 0, 1: 1, 2: 5, 3: -1, 4: -1, 5: 2, 6: -1, 7: -1, 8: 8, 9: -1}

def valid(m1, m2, h1, h2, m, h):
	(nh1, nh2) = (mirror[h1], mirror[h2])
	(nm1, nm2) = (mirror[m1], mirror[m2])
	if -1 in [nm1, nm2, nh1, nh2]:
		return False
	else:
		if 10 * nm2 + nm1 >= h:
			return False
		if 10 * nh2 + nh1 >= m:
			return False
		return True

def next(m1, m2, h1, h2, m, h):
	minute = 10 * m1 + m2
	heure = 10 * h1 + h2
	minute += 1
	heure += minute // m
	minute = minute % m
	heure = heure % h
	return (minute // 10, minute % 10, heure // 10, heure % 10)
for case in range(t):
	(h, m) = map(int, input().split())
	s = input()
	(h1, h2) = map(int, s[:2])
	(m1, m2) = map(int, s[3:])
	while not valid(m1, m2, h1, h2, m, h):
		(m1, m2, h1, h2) = next(m1, m2, h1, h2, m, h)
	print(h1, h2, ':', m1, m2, sep='')


import sys
import bisect
input_ = lambda : sys.stdin.readline().strip('\r\n')
from math import log
ip = lambda : input_()
ii = lambda : int(input_())
sc = lambda : input_().split()
il = lambda : list(map(int, input_().split()))
d = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}
valid = ['0', '1', '2', '5', '8']

def val(a):
	(h1, h2, m1, m2) = (str(a[0] % 10), str(a[0] // 10 % 100), str(a[1] % 10), str(a[1] // 10 % 100))
	if str(a[0] % 10) in valid and str(a[0] // 10 % 100) in valid and (str(a[1] % 10) in valid) and (str(a[1] // 10 % 100) in valid):
		if int(str(d[m1]) + str(d[m2])) < h and int(str(d[h1] + d[h2])) < m:
			return True
	return False
for _ in range(ii()):
	(h, m) = il()
	a = list(map(int, input().split(':')))
	b = a
	if val(a):
		print('0' * (2 - len(str(a[0]))) + str(a[0]) + ':' + '0' * (2 - len(str(a[1]))) + str(a[1]))
		continue
	tot = 0
	ans1 = ''
	while True:
		f = 0
		for i in range(m):
			a[1] += 1
			if a[1] >= m:
				a[1] %= m
				a[0] += 1
				a[0] %= h
			tot += 1
			if val(a):
				ans1 = '0' * (2 - len(str(a[0]))) + str(a[0]) + ':' + '0' * (2 - len(str(a[1]))) + str(a[1])
				f = 1
				break
		if f:
			break
	tot1 = tot
	tot = 0
	while True:
		f = 0
		for i in range(m):
			a[1] -= 1
			if a[1] < 0:
				a[1] %= m
				a[0] -= 1
				a[0] %= h
			tot += 1
			if val(a):
				ans2 = '0' * (2 - len(str(a[0]))) + str(a[0]) + ':' + '0' * (2 - len(str(a[1]))) + str(a[1])
				f = 1
				break
		if f:
			break
	if tot < tot1:
		print(ans2)
		continue
	print(ans1)


t = int(input())
reflection = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}

def reflect(s):
	res = ''
	for c in s:
		if c in reflection:
			res += reflection[c]
		else:
			return None
	return res[::-1]

def isCorrect(h, m, Th, Tm):
	h = '%02d' % h
	nh = reflect(h)
	m = '%02d' % m
	nm = reflect(m)
	if nh is None or nm is None:
		return False
	(nh, nm) = (int(nm), int(nh))
	return nh < Th and nm < Tm
for _ in range(t):
	(Th, Tm) = map(int, input().split())
	s = input().split(':')
	(h, m) = (int(s[0]), int(s[1]))
	while True:
		if isCorrect(h, m, Th, Tm):
			break
		m += 1
		if m == Tm:
			h += 1
			m = 0
			if h == Th:
				h = 0
	print('%02d:%02d' % (h, m))


mir = [-1] * 10
mir[0] = 0
mir[1] = 1
mir[2] = 5
mir[5] = 2
mir[8] = 8
for i in range(int(input())):
	(h, m) = map(int, input().split())
	(hh, mm) = map(int, input().split(':'))
	while True:
		hs = (hh // 10, hh % 10)
		ms = (mm // 10, mm % 10)
		m_ = (mir[hs[1]], mir[hs[0]])
		h_ = (mir[ms[1]], mir[ms[0]])
		if -1 not in m_ and -1 not in h_ and (h_[0] * 10 + h_[1] < h) and (m_[0] * 10 + m_[1] < m):
			print(*hs, ':', *ms, sep='')
			break
		mm += 1
		if mm == m:
			mm = 0
			hh += 1
			if hh == h:
				hh = 0


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush, heappop, heapify
from itertools import permutations, combinations
from itertools import accumulate as ac
mod = int(1000000000.0) + 7
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
out = lambda x: stdout.write(str(x) + '\n')
t = ip()
for _ in range(t):
	(hours, mins) = inp()
	s = ips()
	valid = [0, 1, 2, 5, 8]
	ref = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}
	valid = set(valid)
	hr = int(s[0:2])
	mi = int(s[3:5])
	store_hr = hr
	store_mi = mi
	step1 = 0
	while True:
		ch = set()
		step1 += 1
		if len(str(hr)) == 1:
			hr = '0' + str(hr)
		else:
			hr = str(hr)
		if len(str(mi)) == 1:
			mi = '0' + str(mi)
		else:
			mi = str(mi)
		for i in str(hr):
			ch.add(int(i))
		for i in str(mi):
			ch.add(int(i))
		if len(ch | valid) == len(valid):
			cur = hr + mi
			cur = cur[::-1]
			cur = [ref[i] for i in cur]
			ref_hr = cur[0:2]
			ref_hr = int(''.join(ref_hr))
			ref_mi = cur[2:4]
			ref_mi = int(''.join(ref_mi))
			if int(ref_hr) < hours and int(ref_mi) < mins:
				ans1 = str(hr) + ':' + str(mi)
				break
			else:
				hr = int(hr)
				mi = int(mi)
				mi += 1
				if mi == mins:
					mi = 0
					hr += 1
					if hr == hours:
						hr = 0
		else:
			hr = int(hr)
			mi = int(mi)
			mi += 1
			if mi == mins:
				mi = 0
				hr += 1
				if hr == hours:
					hr = 0
	step2 = 0
	hr = store_hr
	mi = store_mi
	while True:
		ch = set()
		step2 += 1
		if len(str(hr)) == 1:
			hr = '0' + str(hr)
		else:
			hr = str(hr)
		if len(str(mi)) == 1:
			mi = '0' + str(mi)
		else:
			mi = str(mi)
		for i in str(hr):
			ch.add(int(i))
		for i in str(mi):
			ch.add(int(i))
		if len(ch | valid) == len(valid):
			cur = hr + mi
			cur = cur[::-1]
			cur = [ref[i] for i in cur]
			ref_hr = cur[0:2]
			ref_hr = int(''.join(ref_hr))
			ref_mi = cur[2:4]
			ref_mi = int(''.join(ref_mi))
			if int(ref_hr) < hours and int(ref_mi) < mins:
				ans2 = str(hr) + ':' + str(mi)
				break
			else:
				hr = int(hr)
				mi = int(mi)
				mi -= 1
				if mi < 0:
					mi = mins - 1
					hr -= 1
					if hr < 0:
						hr = hours - 1
		else:
			hr = int(hr)
			mi = int(mi)
			mi -= 1
			if mi < 0:
				mi = mins - 1
				hr -= 1
				if hr < 0:
					hr = hours - 1
	if step1 < step2:
		ans = ans1
	else:
		ans = ans2
	print(ans1)


arr = [-1 for i in range(0, 10)]
arr[0] = 0
arr[1] = 1
arr[2] = 5
arr[5] = 2
arr[8] = 8

def check(a, b, h, m):
	if arr[a % 10] == -1 or arr[a // 10] == -1 or arr[b % 10] == -1 or (arr[b // 10] == -1):
		return 0
	else:
		x = arr[b % 10] * 10 + arr[b // 10]
		y = arr[a % 10] * 10 + arr[a // 10]
		if x < h and y < m:
			return 1
		else:
			return 0
t = int(input())
for i in range(t):
	(h, m) = map(int, input().split())
	t = input()
	hr = (ord(t[0]) - ord('0')) * 10 + ord(t[1]) - ord('0')
	mi = (ord(t[3]) - ord('0')) * 10 + ord(t[4]) - ord('0')
	while check(hr, mi, h, m) != 1:
		mi = mi + 1
		if mi == m:
			hr += 1
		mi = mi % m
		hr = hr % h
	print('{:02d}'.format(hr), end=':')
	print('{:02d}'.format(mi))


def inc_time(s, h, m):
	hh = int(s[0:2])
	mm = int(s[3:])
	mm = (mm + 1) % m
	if mm == 0:
		hh = (hh + 1) % h
	if mm < 10:
		mm = '0' + str(mm)
	else:
		mm = str(mm)
	if hh < 10:
		hh = '0' + str(hh)
	else:
		hh = str(hh)
	s = hh + ':' + mm
	return s

def rev_time_is_valid(s, h, m):
	s = list(s)
	s.reverse()
	d = {'2': '5', '5': '2'}
	for i in range(len(s)):
		if s[i] in d:
			s[i] = d[s[i]]
	s = ''.join(s)
	if int(s[:2]) < h:
		if int(s[3:]) < m:
			return True
		else:
			return False
	else:
		return False
t = int(input())
for i in range(t):
	(h, m) = map(int, input().split())
	s = input()
	l = ['0', '1', '2', '5', '8', ':']
	cnt = 0
	while 1:
		for ch in s:
			if ch not in l:
				cnt = 1
				break
		if cnt == 1:
			cnt = 0
			s = inc_time(s, h, m)
		elif rev_time_is_valid(s, h, m):
			print(s)
			break
		else:
			cnt = 1


from sys import stdin

def solve():
	return 0
for _ in range(int(input())):
	(h, m) = [int(i) for i in input().split()]
	s = input()
	m1 = int(s[3])
	m2 = int(s[4])
	h1 = int(s[0])
	h2 = int(s[1])
	vava = [1, 1, 1, 0, 0, 1, 0, 0, 1, 0]
	ref = [0, 1, 5, 0, 0, 2, 0, 0, 8, 0]
	while True:
		if vava[h1] and vava[h2] and vava[m1] and vava[m2]:
			H1 = ref[m2]
			H2 = ref[m1]
			M1 = ref[h2]
			M2 = ref[h1]
			if H1 * 10 + H2 < h and M1 * 10 + M2 < m:
				res = [h1, h2, m1, m2]
				break
			else:
				mins = m1 * 10 + m2
				hours = h1 * 10 + h2
				if mins == m - 1:
					m1 = 0
					m2 = 0
					if hours == h - 1:
						h1 = 0
						h2 = 0
					else:
						hours += 1
						h1 = hours // 10
						h2 = hours % 10
				else:
					mins += 1
					m1 = mins // 10
					m2 = mins % 10
		else:
			mins = m1 * 10 + m2
			hours = h1 * 10 + h2
			if mins == m - 1:
				m1 = 0
				m2 = 0
				if hours == h - 1:
					h1 = 0
					h2 = 0
				else:
					hours += 1
					h1 = hours // 10
					h2 = hours % 10
			else:
				mins += 1
				m1 = mins // 10
				m2 = mins % 10
	print(res[0], end='')
	print(res[1], end='')
	print(':', end='')
	print(res[2], end='')
	print(res[3], end='')
	print()


import math
import sys
import collections
import bisect
import time

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()
import collections
ans = dict()
ans['0'] = '0'
ans['1'] = '1'
ans['2'] = '5'
ans['5'] = '2'
ans['8'] = '8'

def reverse(string):
	string = string[::-1]
	return string

def valid(a, b, h, m):
	for i in a:
		if i not in ans:
			return False
	for i in b:
		if i not in ans:
			return False
	temp_a = ''
	for i in a:
		temp_a += ans[i]
	temp_b = ''
	for i in b:
		temp_b += ans[i]
	a = reverse(temp_a)
	b = reverse(temp_b)
	int_a = int(a)
	int_b = int(b)
	return int_b < h and int_a < m
for t in range(int(input())):
	(h, m) = map(int, input().split())
	x = input()
	a = x[0:2]
	b = x[3:]
	c = 0
	while True:
		if valid(a, b, h, m):
			break
		int_b = (int(b) + 1) % m
		if int_b == 0:
			int_a = (int(a) + 1) % h
		else:
			int_a = int(a)
		a = str(int_a)
		b = str(int_b)
		if len(a) == 1:
			a = '0' + a
		if len(b) == 1:
			b = '0' + b
	sol = a + ':' + b
	print(sol)


T = int(input())
for t in range(T):
	(H, M) = map(int, input().split())
	(h, m) = map(int, input().split(':'))

	def increment(h, m):
		m = (m + 1) % M
		if m == 0:
			h = (h + 1) % H
		return (h, m)
	rmap = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}

	def check(h, m):

		def flip(tstr):
			t = ''
			for digit in reversed(tstr):
				if digit not in rmap:
					return None
				t += rmap[digit]
			return int(t)
		(hs, ms) = ('{:02}'.format(h), '{:02}'.format(m))
		(fm, fh) = (flip(hs), flip(ms))
		return fh is not None and fm is not None and (fh < H) and (fm < M)
	while True:
		if check(h, m):
			print('{:02}:{:02}'.format(h, m))
			break
		(h, m) = increment(h, m)


import math
T = int(input())
ref_d = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]

def getTime(x):
	s = str(x)
	if len(s) == 1:
		s = '0' + s
	ans = ''
	for i in range(1, -1, -1):
		if ref_d[int(s[i])] == -1:
			return math.inf
		ans += str(ref_d[int(s[i])])
	return int(ans)

def convert(x):
	ans = str(x)
	if x < 10:
		ans = '0' + str(x)
	return ans
for _ in range(T):
	(H, M) = [int(e) for e in input().split(' ')]
	(h, m) = [int(e) for e in input().split(':')]
	while True:
		if M == m:
			h += 1
			m = 0
		if H == h:
			h = 0
		if getTime(h) < M and getTime(m) < H:
			print(convert(h) + ':' + convert(m))
			break
		m += 1


refl = {0: 0, 1: 10, 2: 50, 5: 20, 8: 80, 10: 1, 11: 11, 12: 51, 15: 21, 18: 81, 20: 5, 21: 15, 22: 55, 25: 25, 28: 85, 50: 2, 51: 12, 52: 52, 55: 22, 58: 82, 80: 8, 81: 18, 82: 58, 85: 28, 88: 88}

def batao(m, n, a, b):
	return not (m in refl and n in refl and (refl[n] < a) and (refl[m] < b))
for _ in range(int(input())):
	(a, b) = [int(x) for x in input().split(' ')]
	(i, j) = [int(x) for x in input().split(':')]
	if batao(i, j, a, b):
		v = (i * b + j) % (a * b)
		(i, j) = (v // b % a, v % b)
		while batao(i, j, a, b):
			v = (v + 1) % (a * b)
			(i, j) = (v // b % a, v % b)
	print(str(i).zfill(2) + ':' + str(j).zfill(2))


def check(curr):
	(ones, tens) = (curr % 10, curr // 10)
	if ones in d and tens in d:
		return d[ones] * 10 + d[tens]
	return 10 ** 5
d = {1: 1, 2: 5, 5: 2, 8: 8, 0: 0}
for t in range(int(input())):
	(h, m) = map(int, input().split())
	(x, y) = map(int, input().split(':'))
	while True:
		if check(x) < m and check(y) < h:
			break
		y += 1
		if y == m:
			y = 0
			x = (x + 1) % h
	print(str(x).rjust(2, '0') + ':' + str(y).rjust(2, '0'))


l = ['0', '1', '2', '5', '8']

def g(x):
	if x == '2':
		return '5'
	if x == '5':
		return '2'
	return x

def f(x, y, p, q):
	s1 = str(x)
	s2 = str(y)
	for c in s1:
		if c not in l:
			return False
	for c in s2:
		if c not in l:
			return False
	if len(s1) == 1:
		s1 = '0' + s1
	if len(s2) == 1:
		s2 = '0' + s2
	s3 = int(g(s2[1]) + g(s2[0]))
	s4 = int(g(s1[1]) + g(s1[0]))
	if s3 < p and s4 < q:
		return True
	return False
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	s = input()
	x = int(s[:2])
	y = int(s[3:])
	am = False
	while not am:
		while x < h and (not am):
			while y < m and (not am):
				if f(x, y, h, m):
					am = True
					s1 = str(x)
					s2 = str(y)
					if len(s1) == 1:
						s1 = '0' + s1
					if len(s2) == 1:
						s2 = '0' + s2
					print(s1 + ':' + s2)
				y += 1
			if y == m:
				y = 0
			x += 1
		if x == h:
			x = 0


from os import path
import sys, time
from math import ceil, floor, gcd, log, log2, factorial, sqrt
from collections import defaultdict, Counter, OrderedDict, deque
from itertools import combinations, permutations
from bisect import *
from functools import reduce
from operator import mul
maxx = float('inf')
I = lambda : int(sys.stdin.buffer.readline())
lint = lambda : [int(x) for x in sys.stdin.buffer.readline().split()]
S = lambda : sys.stdin.readline().strip('\n')
grid = lambda r: [lint() for i in range(r)]
localsys = 0
start_time = time.time()
nCr = lambda n, r: reduce(mul, range(n - r + 1, n + 1), 1) // factorial(r)

def ceill(n, x):
	return (n + x - 1) // x
T = 1

def ok(s, d, h, m, t):
	(X, s) = ([], '0' * (2 - len(s)) + s)
	for i in s:
		if i not in d:
			return False
		X.append(d[i])
	x = ''.join(X)[::-1]
	if t and int(x) < m or (t == 0 and int(x) < h):
		return True
	return False

def c(s, x):
	return (s + 1) % x

def solve():
	(h, m) = map(int, input().split())
	(s1, s2) = map(int, input().split(':'))
	(d, cnt, c, fl) = ({'1': '1', '2': '5', '5': '2', '8': '8', '0': '0'}, h * m, m, True)
	while cnt:
		if ok(str(s1), d, h, m, 1) and ok(str(s2), d, h, m, 0):
			(s1, s2) = (str(s1), str(s2))
			print('0' * (2 - len(s1)) + s1 + ':' + '0' * (2 - len(s2)) + s2)
			return
			cnt -= 1
		(s2, c) = ((s2 + 1) % m, c - 1)
		if c == 0 or (fl and s2 == 0):
			(c, fl) = (m, False)
			s1 = (s1 + 1) % h
	print('00:00')

def run():
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
run()
T = I() if T else 1
for _ in range(T):
	solve()
if localsys:
	print('\n\nTime Elased :', time.time() - start_time, 'seconds')


rn = lambda : int(input())
rns = lambda : map(int, input().split())
rl = lambda : list(map(int, input().split()))
rs = lambda : input()
YN = lambda x: print('YES') if x else print('NO')
mod = 10 ** 9 + 7
from bisect import bisect_left

def isvalid(i, j, k, l, h, m):
	ans = 10 * int(i) + int(j) < h and 10 * int(k) + int(l) < m

	def reverse(char):
		if char in [1, 0, 8]:
			return char
		if char == 2:
			return 5
		return 2
	rev = [reverse(c) for c in [l, k, j, i]]
	ans = ans and 10 * int(rev[0]) + int(rev[1]) < h and (10 * int(rev[2]) + int(rev[3]) < m)
	return ans
for _ in range(rn()):
	(h, m) = rns()
	s = rs()
	good = [0, 1, 2, 5, 8]
	times = []
	for i in good:
		for j in good:
			for k in good:
				for l in good:
					if isvalid(i, j, k, l, h, m):
						time = str(i) + str(j) + ':' + str(k) + str(l)
						ttime = (10 * int(i) + int(j)) * m + (10 * int(k) + int(l))
						times.append([ttime, time])
	times.sort()
	atimes = [i[0] for i in times]
	find = (10 * int(s[0]) + int(s[1])) * m + (10 * int(s[3]) + int(s[4]))
	i = bisect_left(atimes, find) % len(atimes)
	ans = times[i][1]
	print(ans)


def func(s, n):
	l = {1: 1, 2: 5, 5: 2, 0: 0, 8: 8}
	s1 = s % 10
	s2 = s // 10
	if s1 in l:
		s1 = l[s1]
	else:
		return 0
	if s2 in l:
		s2 = l[s2]
	else:
		return 0
	rs = s1 * 10 + s2
	if rs < n:
		return 1
	else:
		return 0
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = input()
	ans = 0
	h = int(s[0:2])
	m = int(s[3:5])
	while 1:
		if func(h, k) and func(m, n):
			break
		m += 1
		if m == k:
			m = 0
			h += 1
			if h == n:
				h = 0
	print('{:02d}:{:02d}'.format(h, m))


rev = {}
rev['0'] = '0'
rev['1'] = '1'
rev['2'] = '5'
rev['5'] = '2'
rev['8'] = '8'

def ref(a1, a2, h, m):
	s1 = str(a1)
	if len(s1) == 1:
		s1 = '0' + s1
	s2 = str(a2)
	if len(s2) == 1:
		s2 = '0' + s2
	for i in s1:
		if i not in rev.keys():
			return False
	for i in s2:
		if i not in rev.keys():
			return False
	hh = ''
	mm = ''
	for i in s1:
		mm = rev[i] + mm
	for i in s2:
		hh = rev[i] + hh
	if int(mm) < m and int(hh) < h:
		return True
	return False
t = int(input())
while t > 0:
	t -= 1
	(h, m) = map(int, input().split())
	s = input()
	lst = list(map(str, s.split(':')))
	curH = int(lst[0])
	curM = int(lst[1])
	while ref(curH, curM, h, m) == False:
		curM += 1
		if curM == m:
			curH += 1
			curM = 0
		if curH == h:
			curH = 0
	hStr = str(curH)
	mStr = str(curM)
	if len(hStr) == 1:
		hStr = '0' + hStr
	if len(mStr) == 1:
		mStr = '0' + mStr
	print(hStr, end=':')
	print(mStr)


valid = [0, 1, 2, 5, 8]
valid1 = [0, 1, 2, 5, 8, 6]

def opos(x):
	a = x % 10
	b = x // 10
	if a == 2:
		a = 5
	elif a == 5:
		a = 2
	if b == 2:
		b = 5
	elif b == 5:
		b = 2
	return a * 10 + b

def opos1(x):
	a = x % 10
	b = x // 10
	if a == 2:
		a = 5
	elif a == 5:
		a = 2
	elif a == 9:
		a = 6
	elif a == 6:
		a = 9
	if b == 2:
		b = 5
	elif b == 5:
		b = 2
	elif b == 9:
		b = 6
	elif b == 6:
		b = 9
	return a * 10 + b
for _ in range(int(input())):
	(a, b) = map(int, input().split())
	(h, m) = map(int, input().split(':'))
	while 1:
		if h // 10 in valid and h % 10 in valid and (m // 10 in valid) and (m % 10 in valid) and (opos(h) < b) and (opos(m) < a):
			break
		m += 1
		h += m // b
		m = m % b
		h = h % a
	print('0' * (2 - len(str(h))) + str(h) + ':' + '0' * (2 - len(str(m))) + str(m))


validDigits = set([0, 1, 2, 5, 8])
reflections = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}

def isValid(n):
	while n > 0:
		if n % 10 not in validDigits:
			return False
		n //= 10
	return True

def getPaddedTime(n):
	if n > 9:
		return str(n)
	else:
		return '0' + str(n)

def getReflectionTime(s):
	return reflections[s[1]] + reflections[s[0]]

def getNextValidTime(n, a, b):
	n -= 1
	for i in range(a):
		n = (n + 1) % a
		if not isValid(n):
			continue
		ns = getPaddedTime(n)
		nsReflection = getReflectionTime(ns)
		if int(nsReflection) < b:
			return ns

def solve(h, m, s):
	sArr = s.split(':')
	sh = sArr[0]
	sm = sArr[1]
	nh = getNextValidTime(int(sh), h, m)
	nm = '00'
	if nh == sh and sm != '00':
		nm = getNextValidTime(int(sm), m, h)
		if nm == '00':
			nh = getNextValidTime((int(nh) + 1) % h, h, m)
	return nh + ':' + nm
t = int(input())
for tc in range(t):
	(h, m) = map(int, input().split())
	s = input()
	result = solve(h, m, s)
	print(result)


valid = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	(hour, min) = input().split(':')
	while 1:
		if int(min) >= m:
			min = '0'
			hour = str(int(hour) + 1)
			if int(hour) >= h:
				hour = '0'
		min = '0' * (len(min) == 1) + min
		hour = '0' * (len(hour) == 1) + hour
		for i in range(2):
			if int(hour[i]) not in valid or int(min[i]) not in valid:
				min = str(int(min) + 1)
				break
		else:
			if int(str(valid[int(min[1])]) + str(valid[int(min[0])])) >= h:
				min = str(int(min) + 1)
				continue
			if int(str(valid[int(hour[1])]) + str(valid[int(hour[0])])) >= m:
				min = str(int(min) + 1)
				continue
			print(hour + ':' + min)
			break


d = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
a = {*d}
R = lambda x: map(int, input().split(x))
(t,) = R(' ')
while t:
	t -= 1
	(h, m) = R(' ')
	(x, y) = R(':')
	for i in range(h * m):
		r = x * m + y + i
		p = f'{r // m % h:02}'
		s = f'{r % m:02}'
		b = (u, v, w, q) = (*map(int, p + s),)
		if {*b} < a and h > d[q] * 10 + d[w] and (d[v] * 10 + d[u] < m):
			break
	print(p, s, sep=':')


import math, sys
from collections import defaultdict, deque
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')

def I():
	return int(sys.stdin.readline())

def In():
	return map(int, sys.stdin.readline().split())

def Sn():
	return sys.stdin.readline().strip()

def Pr(x):
	sys.stdout.write(str(x) + '\n')

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_gte(a, x):
	i = bi.bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return -1

def main():
	try:
		(h, m) = In()
		(a, b) = Sn().split(':')
		ok = False
		ans = '0000'
		noty = set()
		for i in range(10):
			noty.add(str(i))
		noty.remove('5')
		noty.remove('2')
		noty.remove('0')
		noty.remove('1')
		noty.remove('8')
		mins = int(b)
		for i in range(int(a), h):
			for j in range(mins, m):
				temp = ''
				if i <= 9:
					temp += '0'
					temp += str(i)
				else:
					temp = str(i)
				if j <= 9:
					temp += '0'
					temp += str(j)
				else:
					temp += str(j)
				ok1 = True
				for x in temp:
					if x in noty:
						ok1 = False
				if ok1:
					z = list(temp[::-1])
					for x in range(4):
						if z[x] == '2':
							z[x] = '5'
						elif z[x] == '5':
							z[x] = '2'
					z = ''.join(z)
					if int(z[:2]) < h and int(z[2:4]) < m:
						ans = temp
						ok = True
						break
			mins = 0
			if ok:
				break
		if ok:
			print(ans[:2] + ':' + ans[2:4])
		else:
			print('00:00')
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


def can_mirror(x):
	Q = set([0, 1, 2, 5, 8])
	if x in Q:
		return True
	else:
		return False

def mirror(x):
	if x == 0:
		return 0
	if x == 1:
		return 1
	if x == 2:
		return 5
	if x == 5:
		return 2
	if x == 8:
		return 8
	return 0

def solve():
	(h, m) = map(int, input().split())
	s = input()
	for hh in range(int(s[:2]), h):
		start = int(s[3:]) * (hh == int(s[:2]))
		for mm in range(start, m):
			now_h = hh
			now_m = mm
			can = True
			cnt = 2
			while cnt > 0:
				if can_mirror(now_h % 10) and can_mirror(now_m % 10):
					cnt -= 1
				else:
					can = False
					break
				now_h //= 10
				now_m //= 10
			if not can:
				continue
			new_h = 10 * mirror(mm % 10) + mirror(mm // 10)
			new_m = 10 * mirror(hh % 10) + mirror(hh // 10)
			if new_h < h and new_m < m:
				ans = '0' * (hh < 10) + str(hh) + ':' + '0' * (mm < 10) + str(mm)
				print(ans)
				return
	print('00:00')
for _ in range(int(input())):
	solve()


def chk(cur):
	(one, ten) = (cur % 10, cur // 10)
	if one in d and ten in d:
		return d[one] * 10 + d[ten]
	return 10 ** 5
d = {1: 1, 2: 5, 5: 2, 8: 8, 0: 0}
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	(x, y) = map(int, input().split(':'))
	while True:
		if chk(x) < m and chk(y) < h:
			break
		y += 1
		if y == m:
			y = 0
			x = (x + 1) % h
	print(str(x).rjust(2, '0') + ':' + str(y).rjust(2, '0'))


l = ['0', '1', '2', '5', '8']
for _ in range(int(input())):
	(a, b) = map(int, input().split())
	s = input()
	h = s[:2]
	m = s[3:]
	h = int(h)
	m = int(m)
	f = 0
	ans = ''
	while h < a:
		s1 = str(h)
		s2 = str(m)
		if len(s1) == 1:
			s1 = '0' + s1
		if len(s2) == 1:
			s2 = '0' + s2
		t1 = s1
		t2 = s2
		if s1[0] == '5':
			s1 = '2' + s1[1]
		elif s1[0] == '2':
			s1 = '5' + s1[1]
		if s1[1] == '5':
			s1 = s1[0] + '2'
		elif s1[1] == '2':
			s1 = s1[0] + '5'
		if s2[0] == '5':
			s2 = '2' + s2[1]
		elif s2[0] == '2':
			s2 = '5' + s2[1]
		if s2[1] == '2':
			s2 = s2[0] + '5'
		elif s2[1] == '5':
			s2 = s2[0] + '2'
		if s1[0] in l and s1[1] in l and (s2[0] in l) and (s2[1] in l):
			if int(s2[::-1]) < a and int(s1[::-1]) < b:
				f = 1
				ans = t1 + ':' + t2
				break
		m += 1
		if m >= b:
			m = 0
			h += 1
	if f == 0:
		print('00:00')
	else:
		print(ans)


t = int(input())
for q in range(t):
	(h, m) = map(int, input().split())
	s = input()
	s1 = s[0:2]
	s2 = s[3:5]
	while True:
		s3 = ''
		s4 = ''
		b = True
		for i in range(len(s1) - 1, -1, -1):
			if s1[i] == '0':
				s4 += '0'
			elif s1[i] == '1':
				s4 += '1'
			elif s1[i] == '2':
				s4 += '5'
			elif s1[i] == '5':
				s4 += '2'
			elif s1[i] == '8':
				s4 += '8'
			else:
				b = False
				break
		for i in range(len(s2) - 1, -1, -1):
			if s2[i] == '0':
				s3 += '0'
			elif s2[i] == '1':
				s3 += '1'
			elif s2[i] == '2':
				s3 += '5'
			elif s2[i] == '5':
				s3 += '2'
			elif s2[i] == '8':
				s3 += '8'
			else:
				b = False
				break
		if b:
			hr = int(s3)
			mn = int(s4)
			if hr // h == 0 and mn // m == 0:
				print(s1 + ':' + s2)
				break
		s1 = int(s1)
		s2 = int(s2)
		s1 = (s1 + ((s2 + 1) // m == 1)) % h
		s2 = (s2 + 1) % m
		if s1 < 10:
			s1 = '0' + str(s1)
		else:
			s1 = str(s1)
		if s2 < 10:
			s2 = '0' + str(s2)
		else:
			s2 = str(s2)


reflected = {'0': '0', '1': '1', '2': '5', '3': '-', '4': '-', '5': '2', '6': '-', '7': '-', '8': '8', '9': '-', ':': ':'}

def getReflectedTime(originTime):
	reflectedTime = ''.join(map(lambda digit: reflected[digit], originTime))[::-1]
	if '-' in reflectedTime:
		return None
	return reflectedTime

def getNextMinute(hh, mm, h, m):
	mm += 1
	if mm == m:
		mm = 0
		hh += 1
	if hh == h:
		hh = 0
	return (hh, mm)

def solve():
	(h, m) = map(int, input().split())
	currentTime = input()
	(hh, mm) = map(int, currentTime.split(':'))
	for _ in range(h * m):
		displayedTime = '{:0>2d}:{:0>2d}'.format(hh, mm)
		reflectedTime = getReflectedTime(displayedTime)
		if reflectedTime is not None:
			(rhh, rmm) = map(int, reflectedTime.split(':'))
			if rhh < h and rmm < m:
				print(displayedTime)
				break
		(hh, mm) = getNextMinute(hh, mm, h, m)
t = int(input())
for _ in range(t):
	solve()


def rever(num):
	lis = list(str(num))
	if len(lis) == 1:
		lis = ['0'] + lis
	for i in range(len(lis)):
		if lis[i] == '2':
			lis[i] = '5'
		elif lis[i] == '5':
			lis[i] = '2'
	return int(''.join(lis[::-1]))

def is_beauty(hour, minu, maxh, maxm):
	valid = ['0', '1', '2', '5', '8']
	for i in list(str(hour)):
		if i not in valid:
			return False
	for i in list(str(minu)):
		if i not in valid:
			return False
	(revm, revh) = (rever(hour), rever(minu))
	for i in list(str(revh)):
		if i not in valid:
			return False
	for i in list(str(revm)):
		if i not in valid:
			return False
	if revh >= maxh:
		return False
	if revm >= maxm:
		return False
	return True

def pprint(hr, mi):
	(hr, mi) = (str(hr), str(mi))
	if len(hr) == 1:
		hr = '0' + hr
	if len(mi) == 1:
		mi = '0' + mi
	print(hr + ':' + mi)
for _ in ' ' * int(input()):
	(h, m) = map(int, input().split())
	(ch, cm) = map(int, input().split(':'))
	while True:
		if is_beauty(ch, cm, h, m):
			pprint(ch, cm)
			break
		cm += 1
		if cm >= m:
			cm = 0
			ch += 1
			if ch >= h:
				ch = 0


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
REFLECTIONS = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}

def intArr():
	return map(int, input().split())

def In():
	return int(input())

def check(s):
	for i in s:
		if i not in REFLECTIONS:
			return 0
	return 1

def validity(t1, h, m):
	if 0 <= int(t1[0]) < h and 0 <= int(t1[1]) < m:
		return 1
	return 0

def reflect(t1):
	temp = [0, 0]
	temp[0] = REFLECTIONS[t1[1][1]] + REFLECTIONS[t1[1][0]]
	temp[1] = REFLECTIONS[t1[0][1]] + REFLECTIONS[t1[0][0]]
	return temp.copy()

def incTime(t1, h, m):
	(hr, mi) = (t1[0], t1[1])
	mi = int(mi) + 1
	hr = int(hr)
	hr += mi // m
	mi %= m
	hr %= h
	temp = [str(hr).zfill(2), str(mi).zfill(2)]
	return temp.copy()

def func(h, m, l1):
	curr = l1.copy()
	while 1:
		temp1 = ''.join(curr)
		if check(temp1):
			reflected = reflect(curr)
			if validity(reflected.copy(), h, m):
				return ':'.join(curr)
		curr = incTime(curr, h, m)

def main():
	for _ in range(In()):
		(h, m) = intArr()
		l1 = input().split(':')
		print(func(h, m, l1))
	return
main()


from math import *
import threading
import sys
from collections import defaultdict
from pprint import pprint
sys.setrecursionlimit(300000)
mod = 10 ** 9
inf = 10 ** 15
yes = 'YES'
no = 'NO'
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def npr(n, r):
	return factorial(n) // factorial(n - r) if n >= r else 0

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val):
	ans = -1
	lb = 0
	ub = len(li) - 1
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = mid
			break
	return ans

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	li = []
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, len(prime)):
		if prime[p]:
			li.append(p)
	return li

def primefactors(n):
	factors = []
	while n % 2 == 0:
		factors.append(2)
		n //= 2
	for i in range(3, int(sqrt(n)) + 1, 2):
		while n % i == 0:
			factors.append(i)
			n //= i
	if n > 2:
		factors.append(n)
	return factors

def prod(li):
	ans = 1
	for i in li:
		ans *= i
	return ans

def dist(a, b):
	d = abs(a[1] - b[1]) + abs(a[2] - b[2])
	return d

def power_of_n(x, n):
	cnt = 0
	while x % n == 0:
		cnt += 1
		x //= n
	return cnt

def check(time, temphh, tempmm):
	changed = [0, 1, 5, inf, inf, 2, inf, inf, 8, inf]
	if time[0] > temphh - 1 or time[1] > tempmm - 1:
		return 0
	rev_min = changed[time[0] // 10] + changed[time[0] % 10] * 10
	rev_hour = changed[time[1] // 10] + changed[time[1] % 10] * 10
	if rev_hour > temphh - 1 or rev_min > tempmm - 1:
		return 0
	return 1
for _ in range(int(input()) if True else 1):
	(temphh, tempmm) = map(int, input().split())
	time = list(map(int, input().split(':')))
	f = check(time, temphh, tempmm)
	while not f:
		time[1] += 1
		if time[1] > tempmm - 1:
			time[0] += 1
			if time[0] > temphh - 1 and time[1] > tempmm - 1:
				time[0] = 0
				time[1] = 0
				break
			time[1] = 0
		f = check(time, temphh, tempmm)
	print(str(time[0]).rjust(2, '0') + ':' + str(time[1]).rjust(2, '0'))


valid_numbers = {1: 1, 2: 5, 5: 2, 8: 8, 0: 0}
t = int(input())
for _ in range(0, t):
	(H, M) = map(int, input().split())
	(h, m) = map(int, input().split(':'))
	time = min(H, M)
	hour_plus = False
	hour_change = False
	while 1:
		m_reverse = valid_numbers[m % 10] * 10 if m % 10 in valid_numbers else m % 10 * 10
		m_reverse = m_reverse + valid_numbers[m // 10] if m // 10 in valid_numbers else m // 10
		if m >= M and m_reverse >= H:
			m = 0
			hour_plus = True
			break
		elif m // 10 in valid_numbers and m % 10 in valid_numbers and (m < M) and (m_reverse < H):
			break
		else:
			m += 1
	if hour_plus:
		h += 1
	while 1:
		h_reverse = valid_numbers[h % 10] * 10 if h % 10 in valid_numbers else h % 10 * 10
		h_reverse = h_reverse + valid_numbers[h // 10] if h // 10 in valid_numbers else h // 10
		if h >= H and h_reverse >= M:
			h = 0
			break
		elif h // 10 in valid_numbers and h % 10 in valid_numbers and (h < H) and (h_reverse < M):
			break
		else:
			h += 1
			hour_change = True
	if hour_change:
		m = 0
	print(str(h).zfill(2) + ':' + str(m).zfill(2))


t = int(input())

def check(s):
	if '3' in s:
		return False
	if '4' in s:
		return False
	if '6' in s:
		return False
	if '7' in s:
		return False
	if '9' in s:
		return False
	s = s[::-1]
	s = s.replace('2', '#')
	s = s.replace('5', '2')
	s = s.replace('#', '5')
	nn = s.split(':')
	if int(nn[0]) >= h:
		return False
	if int(nn[1]) >= m:
		return False
	return True

def next_House(s):
	nn = s.split(':')
	next_h = int(nn[0])
	next_m = int(nn[1])
	if next_m == m - 1:
		next_m = 0
		if next_h == h - 1:
			next_h = 0
		else:
			next_h += 1
	else:
		next_m += 1
	s = '0' * (2 - len(str(next_h))) + str(next_h) + ':' + '0' * (2 - len(str(next_m))) + str(next_m)
	return s
for _t in range(t):
	n_k = input().split(' ')
	h = int(n_k[0])
	m = int(n_k[1])
	ss = input()
	while check(ss) == False:
		ss = next_House(ss)
	print(ss)


def isSafe(s, h, m):
	if int(s[:2]) >= h or int(s[3:]) >= m:
		return False
	s = list(s[::-1])
	for i in range(5):
		if s[i] == '2':
			s[i] = '5'
		elif s[i] == '5':
			s[i] = '2'
	s = ''.join(s)
	if int(s[:2]) >= h or int(s[3:]) >= m:
		return False
	for d in ['3', '4', '6', '7', '9']:
		if d in s:
			return False
	return True
t = int(input())
for _ in range(t):
	(h, m) = map(int, input().split())
	s = input().strip()
	val1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
	val2 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
	val3 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
	val4 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
	while val1 and s[0] > val1[0]:
		val1.pop(0)
	while val2 and s[1] > val2[0]:
		val2.pop(0)
	while val3 and s[3] > val3[0]:
		val3.pop(0)
	while val4 and s[4] > val4[0]:
		val4.pop(0)
	ans = None
	for v1 in val1:
		if ans:
			break
		for v2 in val2:
			if ans:
				break
			for v3 in val3:
				if ans:
					break
				for v4 in val4:
					if isSafe(v1 + v2 + ':' + v3 + v4, h, m):
						ans = v1 + v2 + ':' + v3 + v4
						break
				val4 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
			val3 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
		val2 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
	print(ans if ans else '00:00')


a = ['0', '1', '2', '5', '8']

def fun(sh, sm):
	c = 0
	sh = str(sh).rjust(2, '0')[::-1]
	sm = str(sm).rjust(2, '0')[::-1]
	for ele in set(sh + sm):
		if ele not in a:
			c += 1
	if c > 0:
		return False
	else:
		shn = ''
		smn = ''
		for (i, j) in zip(sh, sm):
			if i == '5':
				shn = shn + '2'
			elif i == '2':
				shn = shn + '5'
			else:
				shn = shn + str(i)
			if j == '5':
				smn = smn + '2'
			elif j == '2':
				smn = smn + '5'
			else:
				smn = smn + str(j)
		if int(shn) < mmax and int(smn) < hmax:
			return True
		else:
			return False
for test in range(int(input())):
	(hmax, mmax) = map(int, input().split())
	(sh, sm) = map(int, input().split(':'))
	flag = 0
	while sh % hmax != 0 or sm % mmax != 0:
		if fun(sh, sm):
			print(str(sh).rjust(2, '0') + ':' + str(sm).rjust(2, '0'))
			flag = -1
			break
		sm += 1
		if sm == mmax:
			sm = 0
			sh = sh + 1
	if flag == 0:
		print('00:00')


for i in range(int(input())):
	a = [int(j) for j in input().split()]
	h = a[0]
	m = a[1]
	s = input()
	l1 = ['0', '1', '2', '5', '8']
	l2 = ['0', '1', '5', '2', '8']
	H = s[:2]
	H0 = H
	M = s[3:]
	while int(H) < h:
		if len(str(int(H))) == 1:
			if H == '09':
				H = '10'
			elif H[1] in l1 and int(l2[l1.index(H[1])] + '0') < m:
				break
			else:
				H = '0' + str(int(H[1]) + 1)
		elif H[0] in l1 and H[1] in l1 and (int(l2[l1.index(H[1])] + l2[l1.index(H[0])]) < m):
			break
		else:
			H = str(int(H) + 1)
	if int(H) == h:
		H = '00'
	if H0 == H:
		while int(M) < m:
			if len(str(int(M))) == 1:
				if M == '09':
					M = '10'
				elif M[1] in l1 and int(l2[l1.index(M[1])] + '0') < h:
					break
				else:
					M = '0' + str(int(M[1]) + 1)
			elif M[0] in l1 and M[1] in l1 and (int(l2[l1.index(M[1])] + l2[l1.index(M[0])]) < h):
				break
			else:
				M = str(int(M) + 1)
		if int(M) == m:
			if len(str(int(H))) == 1:
				if H == '09':
					H = '10'
				else:
					H = '0' + str(int(H[1]) + 1)
			elif int(H) == h - 1:
				H = '00'
			else:
				H = str(int(H) + 1)
			while int(H) < h:
				if len(str(int(H))) == 1:
					if H == '09':
						H = '10'
					elif H[1] in l1 and int(l2[l1.index(H[1])] + '0') < m:
						break
					else:
						H = '0' + str(int(H[1]) + 1)
				elif H[0] in l1 and H[1] in l1 and (int(l2[l1.index(H[1])] + l2[l1.index(H[0])]) < m):
					break
				else:
					H = str(int(H) + 1)
			if int(H) == h:
				H = '00'
			M = '00'
			print(H + ':' + M)
		else:
			print(H + ':' + M)
	else:
		print(H + ':' + '00')


import sys
import re
import random
import math
import copy
from heapq import heappush, heappop, heapify
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
getS = lambda : input().strip()
getN = lambda : int(input())
getList = lambda : list(map(int, input().split()))
getZList = lambda : [int(x) - 1 for x in input().split()]
INF = float('inf')
MOD = 10 ** 9 + 7
divide = lambda x: pow(x, MOD - 2, MOD)

def nck(n, k, kaijyo):
	return npk(n, k, kaijyo) * divide(kaijyo[k]) % MOD

def npk(n, k, kaijyo):
	if k == 0 or k == n:
		return n % MOD
	return kaijyo[n] * divide(kaijyo[n - k]) % MOD

def fact_and_inv(SIZE):
	inv = [0] * SIZE
	fac = [0] * SIZE
	finv = [0] * SIZE
	inv[1] = 1
	fac[0] = fac[1] = 1
	finv[0] = finv[1] = 1
	for i in range(2, SIZE):
		inv[i] = MOD - MOD // i * inv[MOD % i] % MOD
		fac[i] = fac[i - 1] * i % MOD
		finv[i] = finv[i - 1] * inv[i] % MOD
	return (fac, finv)

def renritsu(A, Y):
	A = np.matrix(A)
	Y = np.matrix(Y)
	Y = np.reshape(Y, (-1, 1))
	X = np.linalg.solve(A, Y)
	return X.flatten().tolist()[0]

class TwoDimGrid:

	def __init__(self, h, w, wall='#'):
		self.h = h
		self.w = w
		self.size = (h + 2) * (w + 2)
		self.wall = wall
		self.get_grid()

	def get_grid(self):
		grid = [self.wall * (self.w + 2)]
		for i in range(self.h):
			grid.append(self.wall + getS() + self.wall)
		grid.append(self.wall * (self.w + 2))
		self.grid = grid

	def init_cost(self):
		self.cost = [INF] * self.size

	def pos(self, x, y):
		return y * (self.w + 2) + x

	def getgrid(self, x, y):
		return self.grid[y][x]

	def get(self, x, y):
		return self.cost[self.pos(x, y)]

	def set(self, x, y, v):
		self.cost[self.pos(x, y)] = v
		return

	def show(self):
		for i in range(self.h + 2):
			print(self.cost[(self.w + 2) * i:(self.w + 2) * (i + 1)])

	def showsome(self, tgt):
		for t in tgt:
			print(t)
		return

	def showsomejoin(self, tgt):
		for t in tgt:
			print(''.join(t))
		return

	def search(self):
		grid = self.grid
		move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
		move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]

class BIT:

	def __init__(self, n):
		self.n = n
		self.BIT = [0] * (n + 2)

	def query(self, idx):
		res_sum = 0
		while idx > 0:
			res_sum += self.BIT[idx]
			idx -= idx & -idx
		return res_sum

	def update(self, idx, x):
		while idx <= self.n:
			self.BIT[idx] += x
			idx += idx & -idx
		return

	def show(self):
		print(self.BIT)

def judge(t, h, m):
	a = []
	for tt in t:
		if tt in [3, 4, 6, 7, 9]:
			return False
		if tt in [0, 1, 8]:
			a.append(tt)
		if tt == 2:
			a.append(5)
		if tt == 5:
			a.append(2)
	hh = a[3] * 10 + a[2]
	mm = a[1] * 10 + a[0]
	if hh < h and mm < m:
		return True
	else:
		return False

def solve():
	(h, m) = map(int, input().split())
	(a, b) = map(int, input().split(':'))
	while True:
		la = list(str(a))
		if len(la) == 1:
			la = ['0'] + la
		lb = list(str(b))
		if len(lb) == 1:
			lb = ['0'] + lb
		inp = la + lb
		inp = list(map(int, inp))
		res = judge(inp, h, m)
		if res:
			break
		if b < m - 1:
			b += 1
		else:
			a += 1
			b = 0
		if a == h:
			a = 0
	la = list(str(a))
	if len(la) == 1:
		la = ['0'] + la
	lb = list(str(b))
	if len(lb) == 1:
		lb = ['0'] + lb
	print(''.join(la) + ':' + ''.join(lb))

def main():
	n = getN()
	for _ in range(n):
		solve()
	return
main()


data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
reversed_data = [0, 1, 5, 'No', 'No', 2, 'No', 'No', 8, 'No']
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	(hour, minute) = map(int, input().split(':'))
	while True:
		hour0 = hour // 10
		hour1 = hour % 10
		minute0 = minute // 10
		minute1 = minute % 10
		if 'No' not in [reversed_data[hour0], reversed_data[hour1], reversed_data[minute0], reversed_data[minute1]]:
			reversed_hour = reversed_data[minute1] * 10 + reversed_data[minute0]
			reversed_minute = reversed_data[hour1] * 10 + reversed_data[hour0]
			if reversed_hour < h and reversed_minute < m:
				break
			else:
				minute += 1
				if minute == m:
					minute = 0
					hour += 1
					if hour == h:
						hour = 0
		else:
			minute += 1
			if minute == m:
				minute = 0
				hour += 1
				if hour == h:
					hour = 0
	print(str('%02d' % hour) + ':' + str('%02d' % minute))


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def st():
	return input().rstrip('\n')

def lis():
	return list(map(int, input().split()))

def ma():
	return map(int, input().split())
t = inp()
maa = set(['0', '1', '2', '5', '8'])
remap = {'1': '1', '2': '5', '8': '8', '0': '0', '5': '2'}
while t:
	t -= 1
	(h, m) = ma()
	b = input().split(':')
	ch = int(b[0])
	cm = int(b[1])
	while 1:
		chh = str(ch)
		chh = chh.zfill(2)
		cmm = str(cm)
		cmm = cmm.zfill(2)
		if chh[0] in maa and chh[1] in maa and (cmm[0] in maa) and (cmm[1] in maa):
			chh1 = remap[cmm[-1]] + remap[cmm[0]]
			cmm1 = remap[chh[-1]] + remap[chh[0]]
			if int(chh1) < h and int(cmm1) < m:
				print(chh, ':', cmm, sep='')
				break
		cm += 1
		if cm >= m:
			cm = 0
			ch += 1
		if ch >= h:
			ch = 0


ref = {0: '0', 1: '1', 2: '5', 5: '2', 8: '8'}

def turn(x):
	(d_1, d_10) = map(lambda x: ref.get(x, ''), [x // 10, x % 10])
	if d_1 and d_10:
		ret = d_10 + d_1
	else:
		ret = None
	return ret
N = int(input())
for case in range(N):
	(H, M) = map(int, input().split())
	(h, m) = map(int, input().split(':'))
	ret = [0] * 2
	ChangeHour = False
	if turn(h) and int(turn(h)) < M:
		ret[0] = str(h // 10) + str(h % 10)
		for minute in range(m, M):
			new_h = turn(minute)
			if new_h and int(new_h) < H:
				ret[1] = str(minute // 10) + str(minute % 10)
				break
		else:
			ChangeHour = True
			ret[1] = '00'
	else:
		ChangeHour = True
		ret[1] = '00'
	if ChangeHour:
		for hour in range(h + 1, H):
			new_m = turn(hour)
			if new_m and int(new_m) < M:
				ret[0] = str(hour // 10) + str(hour % 10)
				break
		else:
			ret[0] = '00'
	print(ret[0] + ':' + ret[1])


t = int(input())
k = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]
for z in range(t):
	(h, m) = map(int, input().split())
	(a, b) = map(int, input().split(':'))
	s = False
	while 1:
		if a // 10 in k and a % 10 in k and (b // 10 in k) and (b % 10 in k):
			if k[b % 10] * 10 + k[b // 10] < h and k[a % 10] * 10 + k[a // 10] < m:
				print(f'{a // 10}{a % 10}:{b // 10}{b % 10}')
				s = True
		if s:
			break
		b += 1
		if b == m:
			b = 0
			a += 1
		if a == h:
			break
	if not s:
		print('00:00')


def incrementtime(h, m, s):
	t = s.split(':')
	ho = int(t[0])
	mi = int(t[1])
	if mi + 1 < m:
		mi += 1
		return t[0] + ':' + str(mi).zfill(2)
	elif mi + 1 == m:
		temp = '00'
		if ho + 1 < h:
			ho += 1
			return str(ho).zfill(2) + ':' + temp
		elif ho + 1 == h:
			return temp + ':' + temp

def reflect(s):
	t = s.split(':')
	m = [t[0][0], t[0][1], t[1][0], t[1][1]]
	n = []
	for i in m:
		if i == '0':
			n.append('0')
		elif i == '1':
			n.append('1')
		elif i == '2':
			n.append('5')
		elif i == '5':
			n.append('2')
		elif i == '8':
			n.append('8')
	return n[3] + n[2] + ':' + n[1] + n[0]

def checkvalidreflection(h, minutes, s):
	l = ['0', '1', '2', '5', '8']
	t = s.split(':')
	m = [t[0][0], t[0][1], t[1][0], t[1][1]]
	for i in m:
		if i not in l:
			return False
	reflected = reflect(s)
	tr = list(reflected.split(':'))
	h1 = int(tr[0])
	m1 = int(tr[1])
	if h1 < h and m1 < minutes:
		return True
	else:
		return False

def getnearest(h, m, s):
	time = s
	while not checkvalidreflection(h, m, time):
		time = incrementtime(h, m, time)
	return time
t = int(input())
for i in range(t):
	p = input()
	q = p.split(' ')
	h = int(q[0])
	m = int(q[1])
	s = input()
	ans = getnearest(h, m, s)
	print(ans)


reflections = [0, 10, 50, 100, 100, 20, 100, 100, 80, 100, 1, 11, 51, 100, 100, 21, 100, 100, 81, 100, 5, 15, 55, 100, 100, 25, 100, 100, 85, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 2, 12, 52, 100, 100, 22, 100, 100, 82, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 8, 18, 58, 100, 100, 28, 100, 100, 88, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

def pad(hh):
	if hh < 10:
		return f'0{hh}'
	return str(hh)
for _ in range(int(input())):
	flag = False
	(h, m) = map(int, input().split())
	(hh, mm) = map(int, input().split(':'))
	if reflections[hh] < m:
		for mm_ in range(mm, m):
			if reflections[mm_] < h:
				print(f'{pad(hh)}:{pad(mm_)}')
				flag = True
				break
	if flag:
		continue
	for hh_ in range(hh + 1, h):
		for mm_ in range(m):
			if reflections[mm_] < h and reflections[hh_] < m:
				print(f'{pad(hh_)}:{pad(mm_)}')
				flag = True
				break
		if flag:
			break
	if flag:
		continue
	print('00:00')


t = int(input())
for z in range(t):
	(h, m) = map(int, input().split())
	s = input()
	hrs = s[:2]
	mi = s[3:]
	while 1:
		arr = []
		if int(mi) == m:
			mi = 0
			if int(hrs) < h - 1:
				hrs = int(hrs) + 1
			else:
				hrs = 0
		if len(str(hrs)) == 1:
			hrs = '0' + str(hrs)
		if len(str(mi)) == 1:
			mi = '0' + str(mi)
		if '3' not in str(hrs) + str(mi) and '4' not in str(hrs) + str(mi) and ('6' not in str(hrs) + str(mi)) and ('7' not in str(hrs) + str(mi)) and ('9' not in str(hrs) + str(mi)):
			moo = list(str(hrs) + str(mi))
			for i in range(3, -1, -1):
				if moo[i] == '2':
					arr.append('5')
				elif moo[i] == '5':
					arr.append('2')
				else:
					arr.append(moo[i])
			if int(''.join(arr[:2])) < h and int(''.join(arr[2:])) < m:
				break
		mi = int(mi) + 1
	print(''.join(moo[:2]) + ':' + ''.join(moo[2:]))


p = {'5': '2', '2': '5', '1': '1', '0': '0', '8': '8'}
for _ in range(int(input())):
	(h, m) = [int(i) for i in input().split()]
	(a, b) = input().split(':')
	for _ in range(50000):
		if any((e not in p for e in a + b)):
			if int(b) == m - 1:
				if int(a) != h - 1:
					a = '0' * (a[0] == '0') * (a[1] < '9') + str(int(a) + 1)
					b = '00'
					continue
				else:
					a = '00'
					b = '00'
					continue
			else:
				b = '0' * (b[0] == '0') * (b[1] < '9') + str(int(b) + 1)
				continue
		elif int(p[b[1]] + p[b[0]]) < h and int(p[a[1]] + p[a[0]]) < m:
			print(a + ':' + b)
			break
		else:
			if int(b) == m - 1:
				if int(a) != h - 1:
					a = '0' * (a[0] == '0') * (a[1] < '9') + str(int(a) + 1)
					b = '00'
					continue
				else:
					a = '00'
					b = '00'
					continue
			else:
				b = '0' * (b[0] == '0') * (b[1] < '9') + str(int(b) + 1)
			continue


R = dict()
R['0'] = '0'
R['1'] = '1'
R['2'] = '5'
R['5'] = '2'
R['8'] = '8'
for _ in range(int(input())):
	(H, M) = map(int, input().split(' '))
	(h, m) = map(int, input().split(':'))

	def reflect(t):
		h = str(t // M % H).zfill(2)
		m = str(t % M % M).zfill(2)
		try:
			nh = ''.join(map(lambda x: R[x], m[::-1]))
			nm = ''.join(map(lambda x: R[x], h[::-1]))
			return f'{nh}:{nm}'
		except:
			return f'{H:02}:{M:02}'

	def valid(time):
		(h, m) = map(int, time.split(':'))
		return h < H and m < M
	t = h * M + m
	while not valid(reflect(t)):
		t += 1
	h = str(t // M % H).zfill(2)
	m = str(t % M % M).zfill(2)
	print(f'{h}:{m}')


class Clock:

	def __init__(self, h, m, hh, mm):
		self.h = h
		self.m = m
		self.hh = hh
		self.mm = mm

	def xx_str(self, xx):
		return str(xx).zfill(2)

	def __str__(self):
		return self.xx_str(self.hh) + ':' + self.xx_str(self.mm)

	def x_rev(self, x):
		revs = {'0': '0', '1': '1', '2': '5', '3': None, '4': None, '5': '2', '6': None, '7': None, '8': '8', '9': None}
		return revs[x]

	def xx_rev(self, xx):
		first = self.x_rev(xx[1])
		second = self.x_rev(xx[0])
		if first is None or second is None:
			return None
		return first + second

	def check_rev(self):
		hh_rev = self.xx_rev(self.xx_str(self.mm))
		mm_rev = self.xx_rev(self.xx_str(self.hh))
		if hh_rev is None or mm_rev is None:
			return False
		return int(hh_rev) < self.h and int(mm_rev) < self.m

	def inc(self):
		self.mm += 1
		self.hh += self.mm // self.m
		self.mm %= self.m
		self.hh %= self.h

	def inc_untill_rev_correct(self):
		while not self.check_rev():
			self.inc()
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	(hh, mm) = map(int, input().split(':'))
	clock = Clock(h, m, hh, mm)
	clock.inc_untill_rev_correct()
	print(clock)


sigma = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}

def w(q, vba):
	res = ''
	for j in q[::-1]:
		if j in vba.keys():
			res += vba[j]
		else:
			return False
	return res

def y(l):
	if l[0] == '0':
		return int(l[1:])
	else:
		return int(l)

def new(z, c, d):
	if z and y(z[:2]) < c:
		if y(z[2:]) < d:
			return True
	return False
t = int(input())
for i in range(t):
	(h, m) = [int(j) for j in input().split()]
	x = ''.join(input().split(':'))
	cde = w(x, sigma)
	(a, b) = (y(x[:2]), y(x[2:]))
	if cde:
		(abc, qwe) = (y(cde[:2]), y(cde[2:]))
	while not cde or not new(str(abc).zfill(2) + str(qwe).zfill(2), h, m):
		b += 1
		if b == m:
			a += 1
			b = 0
			if a == h:
				a = 0
		cde = w(str(a).zfill(2) + str(b).zfill(2), sigma)
		if cde:
			(abc, qwe) = (y(cde[:2]), y(cde[2:]))
	print(str(a).zfill(2) + ':' + str(b).zfill(2))


t = int(input())

def transform(n):
	return (n // 10, n % 10)

def make(ch, minuts, h, m):
	p = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8, 3: 3, 4: 4, 6: 6, 7: 7, 9: 9}
	bad = {3, 4, 6, 7, 9}
	(qc, rc) = transform(ch)
	(qm, rm) = transform(minuts)
	flag = True
	if not bad.intersection({qc, rc, qm, rm}):
		if p[rm] * 10 + p[qm] < h and p[rc] * 10 + p[qc] < m:
			flag = False
	while flag:
		minuts += 1
		if minuts == m:
			minuts = 0
			ch += 1
		if ch == h:
			ch = 0
		(qc, rc) = transform(ch)
		(qm, rm) = transform(minuts)
		if not bad.intersection({qc, rc, qm, rm}):
			if p[rm] * 10 + p[qm] < h and p[rc] * 10 + p[qc] < m:
				flag = False
	(qc, rc) = transform(ch)
	(qm, rm) = transform(minuts)
	return str(qc) + str(rc) + ':' + str(qm) + str(rm)
for _ in range(t):
	(h, m) = map(int, input().split())
	(ch, minuts) = map(int, input().split(':'))
	print(make(ch, minuts, h, m))


image = {'1': '1', '2': '5', '5': '2', '8': '8', '0': '0'}
has_reflection = {0: True, 1: True, 2: True, 3: False, 4: False, 5: True, 6: False, 7: False, 8: True, 9: False}

def valid_time(time, a, b):
	for t in range(int(time), a):
		t = str(t).zfill(2)
		flag = True
		for i in t:
			if has_reflection[int(i)] == False:
				flag = False
		if flag:
			reflected = ''
			for i in t[::-1]:
				reflected += image[i]
			if int(reflected) < b:
				return t.zfill(2)
	return '00'
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	(hrs, min) = input().split(':')
	new_hrs = valid_time(hrs, h, m)
	if new_hrs == hrs:
		new_min = valid_time(min, m, h)
		if int(new_min) < int(min):
			new_hrs = valid_time(str((int(new_hrs) + 1) % h), h, m)
	else:
		new_min = '00'
	print(new_hrs.zfill(2) + ':' + new_min.zfill(2))


t = int(input())
for _ in range(t):
	(hour, minute) = map(int, input().split())
	(ta, tb) = map(int, input().split(':'))

	def clip(a, b):
		b += 1
		if b == minute:
			a += 1
			b = 0
		if a == hour:
			a = 0
		return (a, b)

	def clock(a, b):
		(a, b) = (str(a), str(b))
		if len(a) < 2:
			a = '0' + a
		if len(b) < 2:
			b = '0' + b
		return (a, b)

	def judge(a, b):
		(a, b) = clock(a, b)
		for letter in '34679':
			if letter in a or letter in b:
				return False
		dic = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}
		aa = dic[b[1]] + dic[b[0]]
		bb = dic[a[1]] + dic[a[0]]
		if int(aa) < hour and int(bb) < minute:
			return True
		return False
	while not judge(ta, tb):
		(ta, tb) = clip(ta, tb)
	print(':'.join(clock(ta, tb)))


def check(time):
	arr = time[:]
	arr[0] = str(arr[0])
	arr[1] = str(arr[1])
	if len(arr[0]) == 1:
		arr[0] = '0' + arr[0]
	if len(arr[1]) == 1:
		arr[1] = '0' + arr[1]
	for x in arr:
		for y in x:
			if dic[y] == '-1':
				return 0
	newarr = [dic[arr[1][1]] + dic[arr[1][0]], dic[arr[0][1]] + dic[arr[0][0]]]
	newarr[0] = int(newarr[0])
	newarr[1] = int(newarr[1])
	if newarr[0] < h and newarr[1] < m:
		return 1
	else:
		return 0

def fun(time):
	arr = time[:]
	arr[0] = str(arr[0])
	arr[1] = str(arr[1])
	if len(arr[0]) == 1:
		arr[0] = '0' + arr[0]
	if len(arr[1]) == 1:
		arr[1] = '0' + arr[1]
	print(*arr, sep=':')
t = int(input())
dic = {'0': '0', '1': '1', '2': '5', '3': '-1', '4': '-1', '5': '2', '6': '-1', '7': '-1', '8': '8', '9': '-1'}
for _ in range(t):
	(h, m) = map(int, input().split())
	time = input().split(':')
	time[0] = int(time[0])
	time[1] = int(time[1])
	c = check(time)
	if c == 1:
		fun(time)
		continue
	for i in range(h * m):
		time[1] += 1
		if time[1] == m:
			time[1] = 0
			time[0] += 1
			if time[0] == h:
				time[0] = 0
		c = check(time)
		if c == 1:
			fun(time)
			break


numbers = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]

def remake(x):
	x = str(x)
	if len(x) == 1:
		x = '0' + x
	return x

def back(x):
	x = remake(x)
	a = ''
	for i in range(1, -1, -1):
		if numbers[int(x[i])] == -1:
			return 300000000000000000000
		else:
			a = a + str(numbers[int(x[i])])
	return int(a)
t = int(input())
for i in range(t):
	s = input()
	(h, m) = (s.split()[0], s.split()[1])
	s = input()
	(H, M) = (s.split(':')[0], s.split(':')[1])
	H = int(H)
	M = int(M)
	m = int(m)
	h = int(h)
	while 1:
		if M == m:
			M = 0
			H = H + 1
		if H == h:
			H = 0
		if back(M) < h and back(H) < m:
			print(remake(H), remake(M), sep=':')
			break
		M = M + 1


a = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]
test = int(input())

def check(x, y, h, m):
	if a[x // 10] == -1 or a[x % 10] == -1 or a[y // 10] == -1 or (a[y % 10] == -1):
		return 0
	if a[x % 10] * 10 + a[x // 10] >= m or a[y % 10] * 10 + a[y // 10] >= h:
		return 0
	return 1

def pnt(x, y):
	res = ''
	if x < 10:
		res += '0'
	res += str(x)
	res += ':'
	if y < 10:
		res += '0'
	res += str(y)
	print(res)
	return 0
for i in range(test):
	(h, m) = map(int, input().split(' '))
	s = input()
	arr = s.split(':')
	x = int(arr[0])
	y = int(arr[1])
	while True:
		if check(x, y, h, m) == 1:
			pnt(x, y)
			break
		else:
			y += 1
			if y >= m:
				y -= m
				x += 1
				if x >= h:
					x -= h


def check(time: list, h: int, m: int) -> bool:
	time_glass = [glass[time[3]], glass[time[2]], glass[time[1]], glass[time[0]]]
	if None in time_glass:
		return False
	if time_glass[0] * 10 + time_glass[1] >= h or time_glass[2] * 10 + time_glass[3] >= m:
		return False
	return True

def time_next(time: list, h: int, m: int) -> list:
	time_h = time[0] * 10 + time[1]
	time_m = time[2] * 10 + time[3] + 1
	if time_m >= m:
		time_m = time_m % m
		time_h = (time_h + 1) % h
	return [time_h // 10, time_h % 10, time_m // 10, time_m % 10]
glass = [0, 1, 5, None, None, 2, None, None, 8, None]
T = int(input())
for i in range(T):
	(h, m) = map(int, input().split())
	s = input()
	time = [int(s[0]), int(s[1]), int(s[3]), int(s[4])]
	while not check(time, h, m):
		time = time_next(time, h, m)
	print(str(time[0]) + str(time[1]) + ':' + str(time[2]) + str(time[3]))


import sys
import math
from math import factorial, inf, gcd
from heapq import *
from functools import *
from itertools import *
from collections import *
from typing import *
sys.setrecursionlimit(10 ** 5)
t = 1
t = int(input())
p = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
n = 5

def f(k, t):
	(a, b) = (k // 10, k % 10)
	return a in p and b in p and (p[b] * 10 + p[a] < t)
for ii in range(t):
	(h, m) = (int(i) for i in input().split())
	(a, b) = (int(i) for i in input().split(':'))
	(ca, cb) = (a, b)
	flag = False
	if f(ca, m):
		for i in range(b, m):
			cb = i
			if f(cb, h):
				flag = True
				break
	if not flag:
		a = (a + 1) % h
		for i in range(h):
			ca = (a + i) % h
			if f(ca, m):
				break
		for i in range(m):
			cb = i
			if f(cb, h):
				break
	print(f'{ca:02d}:{cb:02d}')


T = int(input())

def work():
	(hmax, mmax) = [int(x) for x in input().strip().split()]
	t = input().strip()
	(h, m) = [int(x) for x in t.split(':')]
	swp = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8', ':': ':'}

	def good(h, m):
		cur = f'{h:02d}:{m:02d}'
		if any((c in cur for c in '34679')):
			return False
		ref = ''.join((swp[c] for c in cur))
		(hh, mm) = [int(x) for x in ref[::-1].split(':')]
		return 0 <= hh < hmax and 0 <= mm < mmax
	while not good(h, m):
		m += 1
		if m == mmax:
			h += 1
			m = 0
			if h == hmax:
				h = 0
	print(f'{h:02d}:{m:02d}')
for _ in range(T):
	work()


def is_correct(hourMax, minuteMax, time):
	(h, m) = time.split(':')
	mirrored = {'0': '0', '1': '1', '2': '5', '3': '', '4': '', '5': '2', '6': '', '7': '', '8': '8', '9': ''}
	mirrored_h = mirrored[h[1]] + mirrored[h[0]]
	mirrored_m = mirrored[m[1]] + mirrored[m[0]]
	if len(mirrored_h) == 2 and int(mirrored_h) < minuteMax and (len(mirrored_m) == 2) and (int(mirrored_m) < hourMax):
		return mirrored_m + ':' + mirrored_h
	return False
N = int(input())
for _ in range(N):
	(hourMax, minuteMax) = map(int, input().split())
	(hourNow, minuteNow) = map(int, input().split(':'))
	result = '00:00'
	flag = False
	for hour in range(hourNow, hourMax):
		start = minuteNow if hour == hourNow else 0
		for minute in range(start, minuteMax):
			time = '0' * (2 - len(str(hour))) + str(hour) + ':' + '0' * (2 - len(str(minute))) + str(minute)
			mirrored = is_correct(hourMax, minuteMax, time)
			if mirrored:
				result = time
				flag = True
				break
		if flag:
			break
	print(result)


reflected = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]

def main():

	def reflectTime(h1, h2, m1, m2):
		return [reflected[m2], reflected[m1], reflected[h2], reflected[h1]]

	def checkPossibleTime(h1, h2, m1, m2):
		if -1 in [h1, h2, m1, m2]:
			return False
		hour = 10 * h1 + h2
		minute = 10 * m1 + m2
		if hour > h - 1:
			return False
		if minute > m - 1:
			return False
		return True

	def checkPossibleTimeBoth(h1, h2, m1, m2):
		return checkPossibleTime(h1, h2, m1, m2) and checkPossibleTime(*reflectTime(h1, h2, m1, m2))

	def convertTimeToString(h1, h2, m1, m2):
		return str(h1) + str(h2) + ':' + str(m1) + str(m2)
	allans = []
	t = int(input())
	for _ in range(t):
		(h, m) = readIntArr()
		s = input()
		s = s[:2] + s[3:]
		(h1, h2, m1, m2) = [int(x) for x in s]
		ok = False
		if checkPossibleTimeBoth(h1, h2, m1, m2):
			allans.append(convertTimeToString(h1, h2, m1, m2))
			continue
		for i in range(m2 + 1, 10):
			if checkPossibleTimeBoth(h1, h2, m1, i):
				allans.append(convertTimeToString(h1, h2, m1, i))
				ok = True
				break
		if ok:
			continue
		for i in range(m1 + 1, 10):
			if checkPossibleTimeBoth(h1, h2, i, 0):
				allans.append(convertTimeToString(h1, h2, i, 0))
				ok = True
				break
		if ok:
			continue
		for i in range(h2 + 1, 10):
			if checkPossibleTimeBoth(h1, i, 0, 0):
				allans.append(convertTimeToString(h1, i, 0, 0))
				ok = True
				break
		if ok:
			continue
		for i in range(h1 + 1, 10):
			if checkPossibleTimeBoth(i, 0, 0, 0):
				allans.append(convertTimeToString(i, 0, 0, 0))
				ok = True
				break
		if ok:
			continue
		allans.append(convertTimeToString(0, 0, 0, 0))
	multiLineArrayPrint(allans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultVal, dimensionArr):
	dv = defaultVal
	da = dimensionArr
	if len(da) == 1:
		return [dv for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(x, y):
	print('? {} {}'.format(x, y))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


t = int(input())
checklist = [0, 1, 2, 5, 8]
for i in range(0, t):
	(h, m) = map(int, input().split())
	time = str(input())
	mirror = time[::-1]
	gggg = mirror.replace('2', 'a')
	ggg = gggg.replace('5', 'b')
	aaaa = ggg.replace('b', '2')
	finalmirror = aaaa.replace('a', '5')
	one = int(time[0])
	two = int(time[1])
	three = int(time[3])
	four = int(time[4])
	first = int(finalmirror[:2])
	third = int(finalmirror[3:5])
	realfirst = str(time[:2])
	realthird = str(time[3:5])
	if one in checklist and two in checklist and (three in checklist) and (four in checklist) and (first < h) and (third < m):
		print(time)
	else:
		j = 0
		while j < 202:
			newfirst = int(realfirst)
			newthird = int(realthird)
			newthird += 1
			if newthird == m:
				j = 0
				realthird = '00'
				newthird = 0
				newfirst = newfirst + 1
				if newfirst < 10:
					realfirst = '0' + str(newfirst)
				else:
					realfirst = str(newfirst)
				if newfirst == h:
					print('00:00')
					break
				else:
					ansfirst = realfirst
					ansthird = realthird
					temp = realfirst.replace('2', 'a')
					newtemp = temp.replace('5', 'b')
					new = newtemp.replace('b', '2')
					finalfirst = new.replace('a', '5')
					gett = realthird.replace('2', 'a')
					gettt = gett.replace('5', 'b')
					gott = gettt.replace('b', '2')
					finalthird = gott.replace('a', '5')
					ansconcat = [int(i) for i in str(ansfirst) + str(ansthird)]
					concat = [int(i) for i in str(finalfirst) + str(finalthird)]
					strconcat = ''.join((str(elem) for elem in concat))
					actualmirror = strconcat[::-1]
					newone = concat[0]
					newtwo = concat[1]
					newthree = concat[2]
					newfour = concat[3]
					mirrorfirst = int(actualmirror[:2])
					mirrorthird = int(actualmirror[2:4])
					if newone in checklist and newtwo in checklist and (newthree in checklist) and (newfour in checklist) and (mirrorfirst < h) and (mirrorthird < m):
						answer_str = ''.join(map(str, ansconcat))
						print(answer_str[0:2] + ':' + answer_str[2:4])
						break
			else:
				if newthird < 10:
					realthird = '0' + str(newthird)
				else:
					realthird = str(newthird)
				ansfirst = realfirst
				ansthird = realthird
				temp = realfirst.replace('2', 'a')
				newtemp = temp.replace('5', 'b')
				new = newtemp.replace('b', '2')
				finalfirst = new.replace('a', '5')
				gett = realthird.replace('2', 'a')
				gettt = gett.replace('5', 'b')
				gott = gettt.replace('b', '2')
				finalthird = gott.replace('a', '5')
				ansconcat = [int(i) for i in str(ansfirst) + str(ansthird)]
				concat = [int(i) for i in str(finalfirst) + str(finalthird)]
				newone = concat[0]
				newtwo = concat[1]
				newthree = concat[2]
				newfour = concat[3]
				strconcat = ''.join((str(elem) for elem in concat))
				actualmirror = strconcat[::-1]
				mirrorfirst = int(actualmirror[:2])
				mirrorthird = int(actualmirror[2:4])
				if newone in checklist and newtwo in checklist and (newthree in checklist) and (newfour in checklist) and (mirrorfirst < h) and (mirrorthird < m):
					answer_str = ''.join(map(str, ansconcat))
					print(answer_str[0:2] + ':' + answer_str[2:4])
					break
			j = j + 1


t = int(input())
r_map = {'1': '1', '0': '0', '2': '5', '5': '2', '8': '8'}

def is_correct(hh, mm, h, m):
	hh = str(hh).zfill(2)
	mm = str(mm).zfill(2)
	if not all((x in r_map for x in hh + mm)):
		return False
	hh2 = mm[::-1]
	mm2 = hh[::-1]
	hh3 = [None] * 2
	mm3 = [None] * 2
	for i in range(2):
		hh3[i] = r_map[hh2[i]]
	for i in range(2):
		mm3[i] = r_map[mm2[i]]
	hh2 = ''.join(hh3)
	mm2 = ''.join(mm3)
	if int(mm2) >= m or int(hh2) >= h:
		return False
	return True
for _ in range(t):
	(h, m) = map(int, input().split())
	(hh, mm) = input().split(':')
	hours = int(hh)
	minutes = int(mm)
	for i in range(hours, 3 * h):
		flag = True
		if i == hours:
			jrange = [x for x in range(minutes, m)]
		else:
			jrange = [x for x in range(0, m)]
		for j in jrange:
			i = i % h
			j = j % m
			if is_correct(i, j, h, m):
				i = str(i).zfill(2)
				j = str(j).zfill(2)
				print(f'{i}:{j}')
				flag = False
				break
		if not flag:
			break


for _ in range(int(input())):
	(hh, mm) = map(int, input().split())
	timeTr = []
	inp = input()
	time = [int(inp[0] + inp[1]), int(inp[3] + inp[4])]

	def tTr():
		global time
		global timeTr
		t0 = time[0]
		t1 = time[1]
		timeTr = [time[0] // 10, time[0] % 10, time[1] // 10, time[1] % 10]
	while True:
		tTr()
		while 3 in timeTr or 4 in timeTr or 6 in timeTr or (7 in timeTr) or (9 in timeTr):
			h = time[0]
			m = time[1]
			if m < mm - 1:
				m += 1
			else:
				m = 0
				if h < hh - 1:
					h += 1
				else:
					h = 0
			time = [h, m]
			tTr()
		timeCheck = [timeTr[0], timeTr[1], timeTr[2], timeTr[3]]
		for i in range(4):
			if timeCheck[i] == 2:
				timeCheck[i] = 5
			elif timeCheck[i] == 5:
				timeCheck[i] = 2
		chekH = timeCheck[3] * 10 + timeCheck[2]
		chekM = timeCheck[1] * 10 + timeCheck[0]
		if chekH <= hh - 1 and chekM <= mm - 1:
			h = str(timeTr[0]) + str(timeTr[1])
			m = str(timeTr[2]) + str(timeTr[3])
			print(f'{h}:{m}')
			break
		else:
			time[1] += 1


def check(a, B):
	d = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
	temp2 = 0
	if a // 10 in d and a % 10 in d:
		temp2 = d[a // 10] + d[a % 10] * 10
		if temp2 >= B:
			return 0
	else:
		return 0
	return 1
t = int(input())
for i in range(t):
	(H, M) = [int(i) for i in input().split()]
	(h, m) = [int(i) for i in input().split(':')]
	while check(h, M) == 0 or check(m, H) == 0:
		if m == M - 1:
			m = 0
			if h == H - 1:
				h = 0
			else:
				h += 1
		else:
			m += 1
	ans = ''
	if h < 10:
		ans += '0' + str(h)
	else:
		ans += str(h)
	ans += ':'
	if m < 10:
		ans += '0' + str(m)
	else:
		ans += str(m)
	print(ans)


T = int(input())
c1 = [0, 1, 2, 5, 8]

def f(x):
	return 5 if x == 2 else 2 if x == 5 else x
for i in range(T):
	(h, m) = map(int, input().split())
	(HH, MM) = map(int, input().split(':'))
	while True:
		if HH // 10 in c1 and HH % 10 in c1 and (MM // 10 in c1) and (MM % 10 in c1) and (f(HH % 10) * 10 + f(HH // 10) < m) and (f(MM % 10) * 10 + f(MM // 10) < h):
			break
		MM += 1
		if MM >= m:
			MM = 0
			HH += 1
		if HH >= h:
			HH = 0
	print('0' * (1 if HH // 10 == 0 else 0) + str(HH) + ':' + '0' * (1 if MM // 10 == 0 else 0) + str(MM))


from sys import *
from math import *
from collections import *
from bisect import *
from itertools import *
INF = maxsize

def get_ints():
	return map(int, stdin.readline().strip().split())

def get_array():
	return list(map(int, stdin.readline().strip().split()))

def input():
	return stdin.readline().strip()
mod = 1000000007
ump = {0: '0', 1: '1', 2: '5', 5: '2', 8: '8'}

def isvalid(a, b):
	a = list(a)
	b = list(b)
	for i in range(len(a)):
		if a[i] not in ump.values():
			return False
		else:
			a[i] = ump.get(int(a[i]))
	for i in range(len(b)):
		if b[i] not in ump.values():
			return False
		else:
			b[i] = ump.get(int(b[i]))
	b.reverse()
	a.reverse()
	ax = int(''.join(a))
	bx = int(''.join(b))
	return bx < h and ax < m
for _ in range(int(input())):
	(h, m) = get_ints()
	x = input()
	a = x[:2]
	b = x[3:]
	while True:
		if isvalid(a, b):
			break
		else:
			bint = (int(b) + 1) % m
			aint = 0
			if bint == 0:
				aint = (int(a) + 1) % h
			else:
				aint = int(a)
			a = list(str(aint))
			b = list(str(bint))
			if len(a) == 1:
				a.append('0')
				a.reverse()
			a = ''.join(a)
			if len(b) == 1:
				b.append('0')
				b.reverse()
			b = ''.join(b)
	print(f'{a}:{b}')


T = int(input())
P = {0, 1, 2, 5, 8}
D = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
for i in range(T):
	(h, m) = map(int, input().split())
	(H, M) = map(int, input().split(':'))
	flag = False
	for i in range(H, H + h):
		if flag:
			break
		H2 = i % h % 10
		H1 = i % h // 10
		for j in range(M * (i == H), M + m):
			M2 = j % m % 10
			M1 = j % m // 10
			H2 = (i + j // m) % h % 10
			H1 = (i + j // m) % h // 10
			S = {H1, H2, M2, M1}
			if S <= P and D[M2] * 10 + D[M1] < h and (D[H2] * 10 + D[H1] < m):
				HH = str(H1) + str(H2)
				MM = str(M1) + str(M2)
				flag = True
				break
	print(HH, MM, sep=':')


import sys
input = sys.stdin.readline

def solve():
	mir = [-1] * 10
	mir[0] = 0
	mir[1] = 1
	mir[2] = 5
	mir[5] = 2
	mir[8] = 8
	for i in range(int(input())):
		(h, m) = map(int, input().split())
		(hh, mm) = map(int, input().split(':'))
		while True:
			hs = (hh // 10, hh % 10)
			ms = (mm // 10, mm % 10)
			m_ = (mir[hs[1]], mir[hs[0]])
			h_ = (mir[ms[1]], mir[ms[0]])
			if -1 not in m_ and -1 not in h_ and (h_[0] * 10 + h_[1] < h) and (m_[0] * 10 + m_[1] < m):
				print(*hs, ':', *ms, sep='')
				break
			mm += 1
			if mm == m:
				mm = 0
				hh += 1
				if hh == h:
					hh = 0
solve()


mirrored = [-1] * 10
mirrored[0] = 0
mirrored[1] = 1
mirrored[2] = 5
mirrored[5] = 2
mirrored[8] = 8

def isValid(hour, minute, h, m):
	h2 = hour % 10
	h1 = (hour - h2) // 10
	m2 = minute % 10
	m1 = (minute - m2) // 10
	if mirrored[h2] != -1 and mirrored[h1] != -1 and (mirrored[m2] != -1) and (mirrored[m1] != -1):
		current_h = mirrored[m2] * 10 + mirrored[m1]
		current_m = mirrored[h2] * 10 + mirrored[h1]
		if current_h < h and current_m < m:
			return True
	else:
		return False
T = int(input())
for _ in range(T):
	(h, m) = map(int, input().strip().split())
	time = input()
	current_h = int(time[:2])
	current_m = int(time[3:])
	while True:
		if isValid(current_h, current_m, h, m):
			ans = ''
			if current_h < 10:
				ans += '0'
			ans += str(current_h)
			ans += ':'
			if current_m < 10:
				ans += '0'
			ans += str(current_m)
			print(ans)
			break
		if current_m < m - 1:
			current_m += 1
		elif current_h < h - 1:
			current_h += 1
			current_m = 0
		else:
			current_h = 0
			current_m = 0


reflected = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}
T = int(input())
for tt in range(T):
	(hour_cap, minute_cap) = [int(k) for k in input().split()]
	cur_time = input()
	(cur_hour, cur_minute) = [int(k) for k in cur_time.split(':')]

	def check_valid(cur_hour, cur_minute):
		_hour = cur_minute[::-1]
		_minute = cur_hour[::-1]
		hour = ''
		minute = ''
		for d in _hour:
			if d not in reflected:
				return None
			hour += reflected[d]
		for d in _minute:
			if d not in reflected:
				return None
			minute += reflected[d]
		if int(hour) < hour_cap and int(minute) < minute_cap:
			return hour + ':' + minute
		return None
	cur_m = cur_minute + cur_hour * minute_cap

	def fill(a):
		if a < 10:
			return '0' + str(a)
		else:
			return str(a)
	for m in range(cur_m, cur_m + 100000):
		next_m = m % minute_cap
		next_h = m // minute_cap % hour_cap
		is_valid = check_valid(fill(next_h), fill(next_m))
		if is_valid != None:
			print(fill(next_h) + ':' + fill(next_m))
			break


m = [0, 1, 2, 5, 8]

def f(k):
	return 5 if k == 2 else 2 if k == 5 else k
for i in range(int(input())):
	(h1, m1) = map(int, input().split())
	(h2, m2) = map(int, input().split(':'))
	while 1:
		if m2 % 10 in m and m2 // 10 in m and (f(m2 % 10) * 10 + f(m2 // 10) < h1) and (h2 % 10 in m) and (h2 // 10 in m) and (f(h2 % 10) * 10 + f(h2 // 10) < m1):
			break
		m2 += 1
		if m2 >= m1:
			m2 = 0
			h2 += 1
		if h2 >= h1:
			h2 = 0
	print('0' * (1 if h2 // 10 == 0 else 0) + str(h2) + ':' + '0' * (1 if m2 // 10 == 0 else 0) + str(m2))


import sys
import os.path
from collections import *
import math
import bisect
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = sys.stdin.readline
t = int(input())
nums = Counter({0: 0, 1: 10, 2: 50, 5: 20, 8: 80, 10: 1, 11: 11, 12: 51, 15: 21, 18: 81, 20: 5, 21: 15, 22: 55, 25: 25, 28: 85, 50: 2, 51: 12, 52: 52, 55: 22, 58: 82, 80: 8, 81: 18, 82: 58, 85: 28, 88: 88})
mirror = {1: 1, 0: 0, 2: 5, 5: 2, 8: 8}
while t:
	t -= 1
	(hrs, mins) = [int(x) for x in input().split()]
	s = input().rstrip('\n')
	h = int(s[0:2])
	m = int(s[3:])
	if m:
		while m < mins:
			if nums[m] and nums[m] < hrs:
				break
			m += 1
	if m == mins:
		m = 0
		h = (1 + h) % hrs
	if h:
		while h < hrs:
			if nums[h] and nums[h] < mins:
				break
			h += 1
			m = 0
	if h == hrs:
		h = 0
	a = h % 10
	h //= 10
	b = h % 10
	c = m % 10
	m //= 10
	d = m % 10
	print(b, a, ':', d, c, sep='')


accepted_numbers = [1, 2, 5, 8, 0]
reverse_numbers = {1: 1, 2: 5, 5: 2, 8: 8, 0: 0}

def main_code():
	(h, m) = input().split(' ')
	(h, m) = (int(h), int(m))
	(hn, mn) = input().split(':')
	(hn, mn) = (int(hn), int(mn))
	minimum = 1000000
	time = [0, 0]
	for i in accepted_numbers:
		for j in accepted_numbers:
			for k in accepted_numbers:
				for l in accepted_numbers:
					if 10 * i + j >= h:
						continue
					if 10 * k + l >= m:
						continue
					if 10 * reverse_numbers[l] + reverse_numbers[k] >= h:
						continue
					if 10 * reverse_numbers[j] + reverse_numbers[i] >= m:
						continue
					value = 10 * k + l - mn + m * (10 * i + j - hn)
					if 0 <= value < minimum:
						minimum = value
						time = [10 * i + j, 10 * k + l]
	print(f'{time[0]:02d}:{time[1]:02d}')
no_of_test_cases = int(input())
for i in range(no_of_test_cases):
	main_code()


T = int(input())

def convert(s):
	s = s[::-1]
	s1 = ''
	for z in s:
		if z == '2':
			s1 = s1 + '5'
		elif z == '5':
			s1 = s1 + '2'
		else:
			s1 = s1 + z
	return int(s1)
for x in range(T):
	a = [int(y) for y in input().split()]
	h = a[0]
	m = a[1]
	s = input()
	h1 = s[0:2]
	m1 = s[3:5]
	l = ['0', '1', '2', '5', '8']
	while h1[0] not in l or h1[1] not in l or m1[0] not in l or (m1[1] not in l) or (convert(m1) >= h) or (convert(h1) >= m):
		h1 = int(h1)
		m1 = int(m1)
		m1 = m1 + 1
		if m1 >= m:
			m1 = m1 - m
			h1 = h1 + 1
			if h1 >= h:
				h1 = h1 - h
		h1 = str(h1)
		m1 = str(m1)
		if len(h1) != 2:
			h1 = '0' + h1
		if len(m1) != 2:
			m1 = '0' + m1
	print(h1 + ':' + m1)


import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq

def input():
	return sys.stdin.readline()[:-1]

def is_mirrorable(H, M, h, m):
	D = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
	if not (h % 10 in D and h // 10 in D and (m % 10 in D) and (m // 10 in D)):
		return False
	m1 = D[h % 10] * 10 + D[h // 10]
	h1 = D[m % 10] * 10 + D[m // 10]
	if 0 <= h1 < H and 0 <= m1 < M:
		return True
	else:
		return False

def solve(H, M, S):
	h = int(S[:2])
	m = int(S[3:])
	while True:
		if is_mirrorable(H, M, h, m):
			return f'{h:02d}:{m:02d}'
		m += 1
		if m == M:
			h += 1
			m = 0
			if h == H:
				h = 0

def main():
	T0 = int(input())
	for _ in range(T0):
		(H, M) = map(int, input().split())
		S = input()
		ans = solve(H, M, S)
		print(ans)
main()


mirror = {0: 0, 1: 1, 2: 5, 3: False, 4: False, 5: 2, 6: False, 7: False, 8: 8, 9: False}
table = [[None for j in range(100)] for i in range(100)]
for i in range(100):
	for j in range(100):
		if mirror[j % 10] is False or mirror[i // 10] is False or mirror[i % 10] is False or (mirror[j // 10] is False):
			table[i][j] = [False]
		else:
			table[i][j] = [mirror[j % 10] * 10 + mirror[j // 10], mirror[i % 10] * 10 + mirror[i // 10]]
t = int(input())
for k in range(t):
	(h, m) = list(map(int, input().split()))
	(hour, minute) = list(map(int, input().split(':')))
	found = False
	i = hour
	j = minute
	while not found:
		if table[i][j][0] is not False and table[i][j][1] is not False:
			if table[i][j][0] < h and table[i][j][1] < m:
				found = True
				print(i if i > 9 else '0' + str(i), end='')
				print(':', end='')
				print(j if j > 9 else '0' + str(j))
		j += 1
		if j >= m:
			j = 0
			i += 1
		if i >= h:
			i = 0
			j = 0


import sys
import itertools
import collections

def rs(x=''):
	if len(x) == 0:
		return sys.stdin.readline().strip()
	return input(x).strip()

def ri(x=''):
	return int(rs(x))

def rm(x=''):
	return map(str, rs(x).split())

def rl(x=''):
	return rs(x).split()

def rmi(x=''):
	return map(int, rl(x))

def rli(x=''):
	return [int(val) for val in rl(x)]

def println(val):
	sys.stdout.write(str(val) + '\n')

def mirror(val):
	mirrored = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]
	(a, b) = (val // 10, val % 10)
	if mirrored[a] == -1 or mirrored[b] == -1:
		return -1
	return mirrored[b] * 10 + mirrored[a]

def solve(testCase):
	(h, m) = rmi()
	time = rs()
	(hour, minute) = (time[:2], time[3:])
	hour = int(hour) * m + int(minute)
	while True:
		(h2, m2) = (mirror(hour // m % h), mirror(hour % m))
		(h2, m2) = (m2, h2)
		if h2 >= 0 and m2 >= 0 and (h2 < h) and (m2 < m):
			break
		hour += 1
	h = hour // m % h
	m = hour % m
	ans = []
	if h < 10:
		ans += ['0']
	ans += [str(h), ':']
	if m < 10:
		ans += ['0']
	ans += [str(m)]
	print(''.join(ans))
for _ in range(ri() if 1 else 1):
	solve(_ + 1)


try:
	first = [0, 1, 2, 5, 8]
	second = [0, 1, 5, 2, 8]
	vis = []

	def init():
		for i in range(110):
			vis.append(-1)
		for i in range(5):
			for j in range(5):
				a = first[i]
				b = first[j]
				vis[a * 10 + b] = second[j] * 10 + second[i]

	def check(sh, sm, h, m):
		(e, f) = (vis[sm], vis[sh])
		if e < 0 or f < 0:
			return False
		if e >= h or f >= m:
			return False
		return True
	init()
	test = int(input())
	while test != 0:
		(h, m) = map(int, input().split())
		inp = input().split(':')
		(sh, sm) = (int(inp[0]), int(inp[1]))
		while True:
			if check(sh, sm, h, m):
				if len(str(sh)) == 1:
					sh = '0' + str(sh)
				if len(str(sm)) == 1:
					sm = '0' + str(sm)
				print(sh, end=':')
				print(sm)
				break
			sm += 1
			if sm >= m:
				sm = 0
				sh += 1
			if sh >= h:
				sh = 0
		test -= 1
except EOFError:
	print(' ')


class Time:

	def __init__(self, hh, mm) -> None:
		self.h = str(hh)
		self.m = str(mm)
		self.nh = int(hh)
		self.nm = int(mm)
		if len(self.h) < 2:
			self.h = '0' + self.h
		if len(self.m) < 2:
			self.m = '0' + self.m

	def rev(self):
		return Time(revers(self.m), revers(self.h))

	def p(self):
		print(self.h + ':' + self.m)

	def pp(self):
		print(self.nh, self.nm)

def later(a, b):
	if a.nh > b.nh or (a.nh == b.nh and a.nm >= b.nm):
		return True
	else:
		return False

def revers(s):
	ss = ''
	for i in s:
		if i == '5':
			ss += '2'
		elif i == '2':
			ss += '5'
		else:
			ss += i
	return ''.join((j for j in reversed(ss)))

def ok(t, h, m):
	if t.nh < h and t.nm < m:
		return True
	else:
		return False
for _ in range(int(input())):
	(h, m) = [int(i) for i in input().split(' ')]
	(hh, mm) = [i for i in input().split(':')]
	time = Time(hh, mm)
	v = ['00', '01', '02', '05', '08', '10', '11', '12', '15', '18', '20', '21', '22', '25', '28', '50', '51', '52', '55', '58', '80', '81', '82', '85', '88']
	f = 0
	for i in v:
		for j in v:
			dt = Time(i, j)
			if later(dt, time) and ok(dt, h, m) and ok(dt.rev(), h, m):
				dt.p()
				f = 1
				break
		if f == 1:
			break
	if f == 0:
		print('00:00')


import math
import operator

def lcm(a, b):
	return a / math.gcd(a, b) * b

def nCr(n, r):
	return math.factorial(n) / (math.factorial(r) * math.factorial(n - r))

def isKthBitSet(n, k):
	if n & 1 << k - 1:
		return True
	else:
		return False

def maximalRectangle(matrix):
	if not matrix or not matrix[0]:
		return 0
	n = len(matrix[0])
	height = [0] * (n + 1)
	ans = 0
	for row in matrix:
		for i in range(n):
			height[i] = height[i] + 1 if row[i] == '0' else 0
		stack = [-1]
		for i in range(n + 1):
			while height[i] < height[stack[-1]]:
				h = height[stack.pop()]
				w = i - 1 - stack[-1]
				ans = max(ans, h * w)
			stack.append(i)
	return ans

def matched(str):
	count = 0
	for i in str:
		if i == '(':
			count += 1
		elif i == ')':
			count -= 1
		if count < 0:
			return False
	return count == 0

def isValid(h, m, nh, nm):
	l = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]
	if l[h // 10] == -1 or l[h % 10] == -1 or l[m // 10] == -1 or (l[m % 10] == -1):
		return False
	resh = l[m % 10] * 10 + l[m // 10]
	resm = l[h % 10] * 10 + l[h // 10]
	return resh < nh and resm < nm

def solve():
	(h, m) = map(int, input().split())
	s = input()
	nh = int(s[0] + s[1])
	nm = int(s[3] + s[4])
	while not isValid(nh, nm, h, m):
		if nm == m - 1:
			nh += 1
		nm += 1
		nm = nm % m
		nh = nh % h
	nh = str(nh)
	nm = str(nm)
	if len(nh) == 1:
		nh = '0' + nh
	if len(nm) == 1:
		nm = '0' + nm
	print(nh + ':' + nm)
t = int(input())
while t > 0:
	t -= 1
	solve()


ref = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8', ':': ':'}

def reflect(time):
	return ''.join([ref[time[i]] for i in range(len(time) - 1, -1, -1)])

def check(time):
	if any((num not in ref for num in time)):
		return False
	else:
		return True

def next(num):
	if num in ['2', '3', '4']:
		return '5'
	if num in ['5', '6', '7']:
		return '8'
	if num in ['8', '9']:
		return '0'
	return str(int(num) + 1)

def check_HH(HH, MM):
	while not check(HH) or int(reflect(HH)) >= m or int(HH) >= h:
		if not check(HH[0]):
			HH = next(HH[0]) + '0'
		else:
			HH = HH[0] + next(HH[1])
			if HH[1] == '0':
				HH = next(HH[0]) + HH[1]
		MM = '00'
	return (HH, MM)
cases = int(input())
for case in range(0, cases):
	inputs = [int(x) for x in input().split(' ')]
	time = input()
	HH = time[0:2]
	MM = time[3:]
	h = inputs[0]
	m = inputs[1]
	(HH, MM) = check_HH(HH, MM)
	while not check(MM) or int(reflect(MM)) >= h or int(MM) >= m:
		if not check(MM[0]):
			MM = next(MM[0]) + '0'
			if MM[0] == '0':
				HH = HH[0] + next(HH[1])
				if HH[1] == '0':
					HH = next(HH[0]) + HH[1]
				(HH, MM) = check_HH(HH, MM)
		else:
			MM = MM[0] + next(MM[1])
			if MM[1] == '0':
				MM = next(MM[0]) + MM[1]
				if MM[0] == '0':
					HH = HH[0] + next(HH[1])
					if HH[1] == '0':
						HH = next(HH[0]) + HH[1]
					(HH, MM) = check_HH(HH, MM)
	print(HH + ':' + MM)


_VALID_SET = set(list('01258'))
_REP = {'2': '5', '5': '2'}

def solve(h, m, H, M):
	while h < H:
		while m < M:
			(sh, sm) = (str(h).zfill(2), str(m).zfill(2))
			st = sh + sm
			if set(st) <= _VALID_SET:
				rt = st[::-1]
				if set(rt) <= _VALID_SET:
					rt = ''.join(map(lambda c: _REP[c] if c in _REP else c, rt))
					(rh, rm) = (rt[:2], rt[2:])
					if int(rh) < H and int(rm) < M:
						print(f'{sh}:{sm}')
						return
			m += 1
			if m == M:
				m = 0
				break
		h += 1
		if h == H:
			h = 0
t = int(input())
for _ in range(t):
	(H, M) = list(map(int, input().split()))
	(h, m) = list(map(int, input().split(':')))
	solve(h, m, H, M)


import sys
input = iter(sys.stdin.read().splitlines()).__next__
REFLECTIONS = [0, 1, 5, None, None, 2, None, None, 8, None]

def reflect(hh, mm):
	reflections = list(map(REFLECTIONS.__getitem__, [mm % 10, mm // 10, hh % 10, hh // 10]))
	if None in reflections:
		return None
	return (10 * reflections[0] + reflections[1], 10 * reflections[2] + reflections[3])

def solve():
	(h, m) = map(int, input().split())
	(hh, mm) = map(int, input().split(':'))
	reflection = reflect(hh, mm)
	while reflection is None or reflection[0] >= h or reflection[1] >= m:
		mm += 1
		if mm >= m:
			mm = 0
			hh += 1
			if hh >= h:
				hh = 0
		reflection = reflect(hh, mm)
	return f'{hh // 10}{hh % 10}:{mm // 10}{mm % 10}'
t = int(input())
output = []
for _ in range(t):
	output.append(solve())
print(*output, sep='\n')


for _ in range(int(input())):
	(h, m) = map(int, input().split())
	(x, y) = map(int, input().split(':'))
	s = ['0', '1', '5', '-1', '-1', '2', '-1', '-1', '8', '-1']
	(i, j) = (x, y)
	f = 0
	while i <= h - 1:
		f = 0
		while j <= m - 1:
			(q, w) = (str(i), str(j))
			if len(q) == 1:
				q = '0' + q
			if len(w) == 1:
				w = '0' + w
			(e, r) = ('', '')
			e += s[int(q[1])]
			e += s[int(q[0])]
			r += s[int(w[1])]
			r += s[int(w[0])]
			if '-1' in e or '-1' in r:
				j += 1
				continue
			if int(r) <= h - 1 and int(e) <= m - 1:
				print(q + ':' + w)
				f = 1
				break
			j += 1
		if f == 1:
			break
		j = 0
		i += 1
	if f == 1:
		continue
	print('00:00')


import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List
sys.setrecursionlimit(99999)
dc = {'1': '1', '2': '5', '5': '2', '8': '8', '0': '0', ':': ':'}

def solve():
	(h, m) = map(int, input().split())
	tt = input()
	hs = int(tt[:2])
	ms = int(tt[3:5])
	for d in range(h * m):
		kms = (ms + d) % m
		khs = (hs + (ms + d) // m) % h
		shs = str(khs).zfill(2) + ':' + str(kms).zfill(2)
		if '3' in shs or '7' in shs or '4' in shs or ('6' in shs) or ('9' in shs):
			continue
		rhm = ''
		for c in shs[::-1]:
			rhm += dc[c]
		rhs = int(rhm[:2])
		rms = int(rhm[3:5])
		if rhs < h and rms < m:
			return shs
for _ in range(int(input())):
	print(solve())


t = int(input())
CAN_INVERSE = {'1': '1', '2': '5', '5': '2', '8': '8', '0': '0'}

def is_inversable(num: str):
	num = list(num)
	res = ''
	for char in num[::-1]:
		if char not in CAN_INVERSE:
			return None
		res += CAN_INVERSE[char]
	return res
KEYS = ['0', '1', '2', '5', '8']
POSSIBLE_NUMS = {}
for i in range(5):
	for j in range(5):
		if i == 4 and j == 4:
			next_val = '00'
		elif j == 4:
			next_val = f'{KEYS[i + 1]}0'
		else:
			next_val = f'{KEYS[i]}{KEYS[j + 1]}'
		POSSIBLE_NUMS[f'{KEYS[i]}{KEYS[j]}'] = {'inv': f'{CAN_INVERSE[KEYS[j]]}{CAN_INVERSE[KEYS[i]]}', 'next': next_val}
result = []
for i in range(t):
	(h, m) = [int(x) for x in input().strip().split(' ')]
	(hour, minute) = input().strip().split(':')
	if hour in POSSIBLE_NUMS and int(POSSIBLE_NUMS[hour]['inv']) < m and (minute in POSSIBLE_NUMS) and (int(POSSIBLE_NUMS[minute]['inv']) < h):
		result.append(f'{hour}:{minute}')
	else:
		possible_hours = sorted([x for x in POSSIBLE_NUMS.keys() if int(x) < h and int(POSSIBLE_NUMS[x]['inv']) < m])
		possible_minutes = sorted([x for x in POSSIBLE_NUMS.keys() if int(x) < m and int(POSSIBLE_NUMS[x]['inv']) < h])
		if hour not in possible_hours:
			if hour > possible_hours[-1]:
				new_hour = '00'
			else:
				new_hour = None
				for x in possible_hours:
					if x < hour:
						continue
					else:
						new_hour = x
						break
				if new_hour is None:
					new_hour = '00'
			new_minute = '00'
		elif hour in possible_hours and minute not in possible_minutes:
			update_hour = False
			if minute > possible_minutes[-1]:
				new_minute = '00'
				update_hour = True
			else:
				for x in possible_minutes:
					if x < minute:
						continue
					else:
						new_minute = x
						break
			if update_hour:
				hour = str(int(hour) + 1)
				if len(hour) == 1:
					hour = '0' + hour
				if hour > possible_hours[-1]:
					new_hour = '00'
				else:
					new_hour = None
					for x in possible_hours:
						if x < hour:
							continue
						else:
							new_hour = x
							break
					if new_hour is None:
						new_hour = '00'
			else:
				new_hour = hour
		result.append(f'{new_hour}:{new_minute}')
for line in result:
	print(line)


from math import *
import os
import random
import re
import sys
from itertools import *
m = pow(10, 9) + 7
reverse = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]

def rev(sec):
	(a, b) = (sec // 10, sec % 10)
	if reverse[a] == -1 or reverse[b] == -1:
		return sys.maxsize
	return reverse[b] * 10 + reverse[a]

def digit(sec):
	d = 1
	while True:
		sec //= 10
		if sec == 0:
			break
		d += 1
	return d

def correct(sec):
	if digit(sec) == 1:
		return '0' + str(sec)
	return sec
for t in range(int(input())):
	(h, m) = map(int, input().split())
	(th, tm) = map(int, input().split(':'))
	while True:
		if tm == m:
			th += 1
			tm = 0
		if th == h:
			th = 0
		if rev(th) < m and rev(tm) < h:
			print(f'{correct(th)}:{correct(tm)}')
			break
		tm += 1


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def getKey(item):
	return item[1]

def sort2(l):
	return sorted(l, key=getKey, reverse=True)

def d2(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def ntl(n):
	return [int(i) for i in str(n)]

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def ceil(x, y):
	if x % y == 0:
		return x // y
	else:
		return x // y + 1

def powerMod(x, y, p):
	res = 1
	x %= p
	while y > 0:
		if y & 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def check(x):
	if x in [0, 1, 2, 5, 8]:
		return 1
	return 0

def ans(x, y):
	x1 = ''
	x2 = ''
	if len(str(x)) == 1:
		x1 = '0' + str(x)
	else:
		x1 = str(x)
	if len(str(y)) == 1:
		x2 = '0' + str(y)
	else:
		x2 = str(y)
	print(x1 + ':' + x2)

def main():
	for _ in range(ii()):
		(h, m) = mi()
		s = si()
		x = int(s[0] + s[1])
		y = int(s[3] + s[4])
		f = [0, 1, 2, 5, 8]
		p = -1
		q = -1
		a = x
		b = y
		for j in range(y, m):
			x1 = a // 10
			x2 = a % 10
			num1 = 0
			if x2 == 2:
				x2 = 5
			elif x2 == 5:
				x2 = 2
			if x1 == 2:
				x1 = 5
			elif x1 == 5:
				x1 = 2
			num1 = x2 * 10 + x1
			y1 = b // 10
			y2 = b % 10
			num2 = 0
			if y2 == 2:
				y2 = 5
			elif y2 == 5:
				y2 = 2
			if y1 == 2:
				y1 = 5
			elif y1 == 5:
				y1 = 2
			num2 = y2 * 10 + y1
			if check(y1) and check(y2) and check(x1) and check(x2):
				pass
			else:
				b += 1
				continue
			if num1 < m and num2 < h:
				p = a
				q = b
				break
			b += 1
		if p != -1:
			ans(p, q)
			continue
		a += 1
		b = 0
		for i in range(x + 1, h):
			b = 0
			for j in range(0, m):
				x1 = a // 10
				x2 = a % 10
				num1 = 0
				if x2 == 2:
					x2 = 5
				elif x2 == 5:
					x2 = 2
				if x1 == 2:
					x1 = 5
				elif x1 == 5:
					x1 = 2
				num1 = x2 * 10 + x1
				y1 = b // 10
				y2 = b % 10
				num2 = 0
				if y2 == 2:
					y2 = 5
				elif y2 == 5:
					y2 = 2
				if y1 == 2:
					y1 = 5
				elif y1 == 5:
					y1 = 2
				num2 = y2 * 10 + y1
				if check(y1) and check(y2) and check(x1) and check(x2):
					pass
				else:
					b += 1
					continue
				if num1 < m and num2 < h:
					p = a
					q = b
					break
				b += 1
			a += 1
			if p != -1:
				break
		if p != -1:
			ans(p, q)
			continue
		a = 0
		b = 0
		for i in range(h):
			b = 0
			for j in range(m):
				x1 = a // 10
				x2 = a % 10
				num1 = 0
				if x2 == 2:
					x2 = 5
				elif x2 == 5:
					x2 = 2
				if x1 == 2:
					x1 = 5
				elif x1 == 5:
					x1 = 2
				num1 = x2 * 10 + x1
				y1 = b // 10
				y2 = b % 10
				num2 = 0
				if y2 == 2:
					y2 = 5
				elif y2 == 5:
					y2 = 2
				if y1 == 2:
					y1 = 5
				elif y1 == 5:
					y1 = 2
				num2 = y2 * 10 + y1
				if check(y1) and check(y2) and check(x1) and check(x2):
					pass
				else:
					b += 1
					continue
				if num1 < m and num2 < h:
					p = a
					q = b
					break
				b += 1
			a += 1
			if p != -1:
				break
		if p != -1:
			ans(p, q)
			continue
		a = h
		b = 0
		for j in range(m):
			x1 = a // 10
			x2 = a % 10
			num1 = 0
			if x2 == 2:
				x2 = 5
			elif x2 == 5:
				x2 = 2
			if x1 == 2:
				x1 = 5
			elif x1 == 5:
				x1 = 2
			num1 = x2 * 10 + x1
			y1 = b // 10
			y2 = b % 10
			num2 = 0
			if y2 == 2:
				y2 = 5
			elif y2 == 5:
				y2 = 2
			if y1 == 2:
				y1 = 5
			elif y1 == 5:
				y1 = 2
			num2 = y2 * 10 + y1
			if check(y1) and check(y2) and check(x1) and check(x2):
				pass
			else:
				b += 1
				continue
			if num1 < m and num2 < h:
				p = a
				q = b
				break
			b += 1
		if p != -1:
			ans(p, q)
			continue
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from sys import stdin
input = stdin.readline

def inc(a):
	p = a[:]
	p[1] = (p[1] + 1) % m
	if p[1] == 0:
		p[0] = (p[0] + 1) % h
	return p

def test(a):
	p = a[:]
	p[0] = str(p[0])
	p[1] = str(p[1])
	for i in range(2):
		if len(p[i]) == 2:
			p[i] = p[i][::-1]
		else:
			assert len(p[i]) == 1
			p[i] = p[i] + '0'
	(p[0], p[1]) = (p[1], p[0])
	for i in range(2):
		for j in range(2):
			if p[i][j] == '2':
				if j == 0:
					p[i] = '5' + p[i][1]
				else:
					p[i] = p[i][0] + '5'
			elif p[i][j] == '5':
				if j == 0:
					p[i] = '2' + p[i][1]
				else:
					p[i] = p[i][0] + '2'
	for i in range(2):
		for j in p[i]:
			if j in bad:
				return False
	p[0] = int(p[0])
	p[1] = int(p[1])
	return p[0] < h and p[1] < m
bad = '34679'
for tt in range(int(input())):
	(h, m) = map(int, input().split())
	s = input()
	(l, r) = (int(s[:2]), int(s[3:]))
	st = [l, r]
	while True:
		if test(st):
			st[0] = str(st[0])
			st[1] = str(st[1])
			if len(st[0]) == 1:
				st[0] = '0' + st[0]
			if len(st[1]) == 1:
				st[1] = '0' + st[1]
			print(st[0] + ':' + st[1])
			break
		st = inc(st)


d = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}

def miror(a, b):
	xa = a // 10
	ya = a % 10
	xb = b // 10
	yb = b % 10
	if xa not in d:
		return (100, 100)
	if ya not in d:
		return (100, 100)
	if xb not in d:
		return (100, 100)
	if yb not in d:
		return (100, 100)
	return (d[yb] * 10 + d[xb], d[ya] * 10 + d[xa])
t = int(input())
for q in range(t):
	ch = input()
	L = [int(i) for i in ch.split()]
	(h, m) = (L[0], L[1])
	ch = input()
	L = [int(i) for i in ch.split(':')]
	(a, b) = (L[0], L[1])
	while True:
		if miror(a, b)[0] < h and miror(a, b)[1] < m:
			break
		b += 1
		if b >= m:
			b = 0
			a += 1
		if a >= h:
			a = 0
	if a < 10:
		ch1 = '0' + str(a)
	else:
		ch1 = str(a)
	if b < 10:
		ch2 = '0' + str(b)
	else:
		ch2 = str(b)
	print(ch1 + ':' + ch2)


I = lambda x: [*map(int, input().split(x))]
for _ in ' ' * I(' ')[0]:
	(hh, mm) = I(' ')
	(h, m) = I(':')
	convert = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]
	while 1:
		ah = convert[h // 10]
		bh = convert[h % 10]
		am = convert[m // 10]
		bm = convert[m % 10]
		H = 10 * bm + am
		M = 10 * bh + ah
		if -1 in [ah, bh, am, bm] or H >= hh or M >= mm:
			m = (m + 1) % mm
			if m == 0:
				h = (h + 1) % hh
			continue
		else:
			print('0' * (h < 10) + str(h) + ':' + '0' * (m < 10) + str(m))
			break


import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz/'
M = 1000000007
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]

def change(s):
	toret = ''
	for x in s:
		if x == '2':
			toret += '5'
		elif x == '5':
			toret += '2'
		else:
			toret += x
	return toret

def isvalid(s, h, m):
	if '3' in s or '4' in s or '6' in s or ('7' in s) or ('9' in s):
		return False
	else:
		(time, mnt) = map(int, change(s[::-1]).split(':'))
		if time <= h - 1 and mnt <= m - 1:
			return True
for _ in range(int(input())):
	(h, m) = map(int, input().split(' '))
	(hrs, mnt) = map(int, input().split(':'))
	totime = h * m + 1
	curtime = hrs * m + mnt
	ans = str(hrs) + ':' + str(mnt)
	for x in range(totime + 1):
		curh = curtime // m % h
		curm = curtime % m
		scurh = str(curh)
		scurm = str(curm)
		if len(scurh) < 2:
			scurh = '0' + scurh
		if len(scurm) < 2:
			scurm = '0' + scurm
		if isvalid(scurh + ':' + scurm, h, m) == True:
			find = True
			ans = str(scurh) + ':' + str(scurm)
			break
		curtime += 1
	print(ans)


def abc(a, b):
	(aa, bb) = (a, b)
	x = 0
	y = 0
	while a:
		z = a % 10
		if d[z] == -1:
			return 0
		else:
			x = x * 10 + d[z]
		a = a // 10
	while b:
		z = b % 10
		if d[z] == -1:
			return 0
		else:
			y = y * 10 + d[z]
		b = b // 10
	if len(str(aa)) == 1:
		x = x * 10
	if len(str(bb)) == 1:
		y = y * 10
	return y < h and x < m
d = {}
d[0] = 0
d[1] = 1
d[2] = 5
d[3] = -1
d[4] = -1
d[5] = 2
d[6] = -1
d[7] = -1
d[8] = 8
d[9] = -1
(h, m) = (0, 0)
t = int(input())
for _ in range(t):
	(h, m) = map(int, input().split())
	(a, b) = map(int, input().split(':'))
	while True:
		if abc(a, b):
			if len(str(a)) == 1:
				a = '0' + str(a)
			else:
				a = str(a)
			if len(str(b)) == 1:
				b = '0' + str(b)
			else:
				b = str(b)
			print(a, b, sep=':')
			break
		b = (b + 1) % m
		if b == 0:
			a = (a + 1) % h


n1 = int(input())

def reflect(s):
	(s1, s2) = (int(s[0]), int(s[1]))
	if s1 in [3, 4, 6, 7, 9] or s2 in [3, 4, 6, 7, 9]:
		return -1
	else:
		d = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
		temp = s1
		s1 = d[s2]
		s2 = d[temp]
		s = str(10 * s1 + s2)
		return s

def check(a, amax):
	if int(reflect(a)) == -1:
		return False
	elif int(reflect(a)) >= int(amax):
		return False
	else:
		return True
for _ in range(n1):
	t1 = [int(item) for item in input().split()]
	(hmax, mmax) = (t1[0], t1[1])
	t2 = [item for item in input().split(':')]
	(h, m) = (t2[0], t2[1])
	hinp = h
	while True:
		if check(h, mmax) is True and check(m, hmax) is True:
			break
		m = (int(m) + 1) % mmax
		if m == 0:
			h = (int(h) + 1) % hmax
			if h == 0:
				h = '00'
			elif h < 10:
				h = '0' + str(h)
			else:
				h = str(h)
			m = '00'
		elif m < 10:
			m = '0' + str(m)
		else:
			m = str(m)
	print(h + ':' + m)


import sys, functools, collections, bisect, math, heapq
input = sys.stdin.readline
mirror = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}

@functools.lru_cache(None)
def fun(i):
	ones = i % 10
	i //= 10
	tens = i % 10
	if ones in mirror:
		newten = mirror[ones]
	else:
		return None
	if tens in mirror:
		newone = mirror[tens]
	else:
		return None
	return str(newten) + str(newone)
t = int(input())
for _ in range(t):
	(h, m) = map(int, input().strip().split())
	(hour, minute) = map(int, input().strip().split(':'))
	while True:
		currhour = fun(minute)
		currminute = fun(hour)
		if currhour and currminute and (int(currhour) < h) and (int(currminute) < m):
			print(str(hour).zfill(2) + ':' + str(minute).zfill(2))
			break
		minute += 1
		if minute >= m:
			minute = 0
			hour += 1
		if hour >= h:
			hour = 0
			minute = 0


for _ in range(int(input())):
	(h, m) = map(int, input().split())
	(x, y) = map(int, input().split(':'))
	s = '01258'

	def fff(x, y, h, m):
		(x, y) = (str(x), str(y))
		if len(x) < 2:
			x = '0' + x
		if len(y) < 2:
			y = '0' + y
		if x[0] not in s or y[0] not in s or x[1] not in s or (y[1] not in s):
			return False
		x = x.replace('5', '-1')
		x = x.replace('2', '5')
		x = x.replace('-1', '2')
		y = y.replace('5', '-1')
		y = y.replace('2', '5')
		y = y.replace('-1', '2')
		return int(x[::-1]) < m and int(y[::-1]) < h
	while not fff(x, y, h, m):
		y += 1
		if y == m:
			y = 0
			x += 1
			if x == h:
				x = 0
	if x < 10:
		print('0%d' % x, end=':')
	else:
		print(x, end=':')
	if y < 10:
		print('0%d' % y)
	else:
		print(y)


def isvalid(s1, s2):
	s1 = str(s1)
	s2 = str(s2)
	if len(s1) != 2:
		s1 = '0' + s1
	if len(s2) != 2:
		s2 = '0' + s2
	a = 0
	for i in range(2):
		if s1[1 - i] not in d.keys():
			return 0
		a = a * 10 + d[s1[1 - i]]
	b = 0
	for i in range(2):
		if s2[1 - i] not in d.keys():
			return 0
		b = b * 10 + d[s2[1 - i]]
	if b < h and a < m:
		return 1
	return 0
d = {'0': 0, '1': 1, '2': 5, '5': 2, '8': 8}
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	s = input()
	(a, b) = s.split(':')
	a = int(a)
	b = int(b)
	f = 0
	for i in range(a, h):
		if i != a:
			b = 0
		for j in range(b, m):
			if isvalid(i, j):
				f = 1
				s1 = str(i)
				s2 = str(j)
				if len(s1) != 2:
					s1 = '0' + s1
				if len(s2) != 2:
					s2 = '0' + s2
				print(s1 + ':' + s2)
				break
		if f == 1:
			break
	if f == 0:
		print('00:00')


import math
d = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}

def standardize(s, h, m):
	if s[1] == m:
		s[1] = 0
		s[0] += 1
	if s[0] == h:
		s[0] = 0
		s[1] = 0
	return s

def get_next_time(s, h, m):
	s = standardize(s, h, m)
	s[1] += 1
	return standardize(s, h, m)

def is_valid(s, h, m):
	if s[0] >= h:
		return False
	if s[1] >= m:
		return False
	return True

def is_mirror_poss(s):
	mirror = [list(str(s[1])), ':', list(str(s[0]))]
	mirror[0] = mirror[0][::-1]
	mirror[2] = mirror[2][::-1]
	for i in range(len(mirror[0])):
		if int(mirror[0][i]) in d:
			pass
		else:
			return False
	for i in range(len(mirror[2])):
		if int(mirror[2][i]) in d:
			pass
		else:
			return False
	return True

def get_mirror(s):
	final = []
	if len(str(s[0])) == 1:
		final.append('0')
		final.append(str(s[0]))
	else:
		final.append(str(s[0]))
	if len(str(s[1])) == 1:
		final.append('0')
		final.append(str(s[1]))
	else:
		final.append(str(s[1]))
	final = ''.join(final)
	s = [final[0:2], final[2:]]
	mirror = [list(str(s[1])), ':', list(str(s[0]))]
	mirror[0] = mirror[0][::-1]
	mirror[2] = mirror[2][::-1]
	for i in range(len(mirror[0])):
		if int(mirror[0][i]) in d:
			mirror[0][i] = str(int(d[int(mirror[0][i])]))
	for i in range(len(mirror[2])):
		if int(mirror[2][i]) in d:
			mirror[2][i] = str(int(d[int(mirror[2][i])]))
	mirror = [''.join(mirror[0]), ''.join(mirror[2])]
	mirror = [int(mirror[0]), int(mirror[1])]
	return mirror

def get_sol(s, h, m):
	t = [s[0], s[1]]
	while True:
		if is_mirror_poss(t):
			mirror = get_mirror(t)
			if is_valid(mirror, h, m):
				final = []
				if len(str(t[0])) == 1:
					final.append('0')
					final.append(str(t[0]))
				else:
					final.append(str(t[0]))
				if len(str(t[1])) == 1:
					final.append('0')
					final.append(str(t[1]))
				else:
					final.append(str(t[1]))
				final = ''.join(final)
				return ''.join([final[0], final[1], ':', final[2], final[3]])
		t = get_next_time(t, h, m)
for t in range(int(input())):
	(h, m) = map(int, input().split())
	s = input()
	s = s.split(':')
	print(get_sol([int(s[0]), int(s[1])], h, m))


def r(str):
	s = ''
	for i in str:
		if i == '2':
			s = '5' + s
		elif i == '5':
			s = '2' + s
		else:
			s = i + s
	return s

def solve():
	l1 = list(input().split())
	h = l1[0]
	m = l1[1]
	l2 = list(input().split(':'))
	h1 = l2[0]
	m1 = l2[1]
	valid = ['1', '2', '5', '8', '0', '00', '01', '02', '05', '08', '10', '11', '12', '15', '18', '20', '21', '22', '25', '28', '50', '51', '52', '55', '58', '80', '81', '82', '85', '88', '100']
	if (h1 in valid and int(r(h1)) < int(m)) and (m1 in valid and int(r(m1)) < int(h)):
		print(h1 + ':' + m1)
	elif h1 not in valid or int(r(h1)) >= int(m):
		while h1 not in valid or int(r(h1)) >= int(m):
			h1 = str((int(h1) + 1) % int(h))
			if int(h1) in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
				h1 = '0' + h1
		if int(h1) in [0, 1, 2, 5, 8]:
			print('0{}:00'.format(int(h1)))
		else:
			print('{}:00'.format(h1))
	else:
		while m1 not in valid or int(r(m1)) >= int(h):
			m1 = str((int(m1) + 1) % int(m))
			if int(m1) in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
				m1 = '0' + m1
			if int(m1) == 0:
				break
		if int(m1) == 0:
			h1 = str((int(h1) + 1) % int(h))
			if int(h1) in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
				h1 = '0' + h1
			while h1 not in valid or int(r(h1)) >= int(m):
				h1 = str((int(h1) + 1) % int(h))
				if int(h1) in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
					h1 = '0' + h1
			if int(h1) in [0, 1, 2, 5, 8]:
				print('0{}:00'.format(int(h1)))
			else:
				print('{}:00'.format(h1))
		elif int(m1) in [1, 2, 5, 8]:
			print('{}:0{}'.format(h1, int(m1)))
		else:
			print('{}:{}'.format(h1, m1))
t = int(input())
while t:
	solve()
	t = t - 1


def reflective(newh, newm, th, tm):
	r = '01258'
	if not (str(newh // 10) in r and str(newh % 10) in r):
		return False
	if not (str(newm // 10) in r and str(newm % 10) in r):
		return False
	newm = str(newm).zfill(2)[::-1]
	newh = str(newh).zfill(2)[::-1]
	nm = ''
	nh = ''
	for ch in newm:
		if ch == '5':
			nm += '2'
		elif ch == '2':
			nm += '5'
		else:
			nm += ch
	for ch in newh:
		if ch == '5':
			nh += '2'
		elif ch == '2':
			nh += '5'
		else:
			nh += ch
	newm = nm
	newh = nh
	if not (int(newm) < th and int(newh) < tm):
		return False
	return True
t = int(input())
for _ in range(t):
	(th, tm) = [int(x) for x in input().split()]
	(h, m) = [int(x) for x in input().split(':')]
	flag = True
	for i in range(th):
		for j in range(tm):
			newm = (m + j) % tm
			newh = (h + i + (m + j) // tm) % th
			if reflective(newh, newm, th, tm):
				t = str(newh).zfill(2) + ':' + str(newm).zfill(2)
				print(t)
				flag = False
				break
		if not flag:
			break


import sys
input = sys.stdin.readline

def calc(n):
	d = ''
	for i in str(n):
		if i == '2':
			d += '5'
		elif i == '5':
			d += '2'
		else:
			d += i
	return d.rjust(2, '0')[::-1]
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	s = input()[:-1]
	a = int(s[:2])
	b = int(s[3:])
	while 1:
		x = calc(a)
		y = calc(b)
		if all((1 if i in ['0', '1', '2', '5', '8'] else 0 for i in x)) and all((1 if i in ['0', '1', '2', '5', '8'] else 0 for i in y)) and (int(x) < m) and (int(y) < h):
			break
		b += 1
		if b == m:
			a += 1
			b = 0
			a %= h
	print(str(a).rjust(2, '0') + ':' + str(b).rjust(2, '0'))


for _ in range(int(input())):
	(h, m) = map(int, input().split())
	s = input()
	hr = 0
	minute = 0
	valid = [0, 1, 5, 0, 0, 2, 0, 0, 8, 0]
	flag = 0
	for i in range(int(s[0] + s[1]), h):
		if i % 10 in valid and int(i / 10) in valid and (int(str(valid[i % 10]) + str(valid[int(i / 10)])) < m):
			if i == int(s[0] + s[1]):
				for j in range(int(s[3] + s[4]), m):
					if j % 10 in valid and int(j / 10) in valid and (int(str(valid[j % 10]) + str(valid[int(j / 10)])) < h):
						minute = j
						hr = i
						flag = 1
						break
			else:
				for j in range(0, m):
					if j % 10 in valid and int(j / 10) in valid and (int(str(valid[j % 10]) + str(valid[int(j / 10)])) < h):
						minute = j
						hr = i
						flag = 1
						break
		if flag:
			break
	if hr < 10:
		print('0', end='')
		print(hr, end='')
	else:
		print(hr, end='')
	print(':', end='')
	if minute < 10:
		print('0', end='')
		print(minute, end='')
	else:
		print(minute, end='')
	print('')


def he(n):
	x = n % 10
	y = n // 10
	a = 0
	b = 0
	if x == 0:
		a = 0
	elif x == 1:
		a = 1
	elif x == 5:
		a = 2
	elif x == 2:
		a = 5
	elif x == 8:
		a = 8
	else:
		return -1
	if y == 0:
		b = 0
	elif y == 1:
		b = 1
	elif y == 5:
		b = 2
	elif y == 2:
		b = 5
	elif y == 8:
		b = 8
	else:
		return -1
	return 10 * a + b

def hel(x, y, h, m):
	a = x
	b = y
	while True:
		if he(a) != -1 and he(b) != -1 and (he(a) < m) and (he(b) < h):
			return (a, b)
		else:
			b += 1
		if b == m:
			b = 0
			a += 1
		if a == h:
			a = 0
t = int(input())
for i in range(t):
	arr = [int(i) for i in input().split()]
	h = arr[0]
	m = arr[1]
	s = input()
	x = s[0:2]
	y = s[3:]
	x = int(x)
	y = int(y)
	p = hel(x, y, h, m)
	ah = p[0]
	am = p[1]
	ah = str(ah)
	am = str(am)
	if len(ah) == 1:
		ah = '0' + ah
	if len(am) == 1:
		am = '0' + am
	s = ah + ':' + am
	print(s)


import string
t = int(input())
while t > 0:
	(H, M) = list(map(int, input().split(' ')))
	(h, m) = list(map(int, input().split(':')))
	for i in range(h * M + m, (h + H) * M + m):
		h_ = str(i // M % H).zfill(2)
		m_ = str(i % M).zfill(2)
		ok = True
		for j in ['3', '4', '6', '7', '9']:
			if j in h_ or j in m_:
				ok = False
				break
		if ok:
			H_ = int(h_.translate(str.maketrans('25', '52'))[::-1])
			M_ = int(m_.translate(str.maketrans('25', '52'))[::-1])
			if M_ < H and H_ < M:
				print(h_ + ':' + m_)
				break
	t -= 1


from sys import stdin, stdout
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import *
input = stdin.readline
from random import sample
t = int(input())
from collections import Counter, deque
from math import sqrt, ceil, log2, gcd

class DisjSet:

	def __init__(self, n):
		self.rank = [1] * n
		self.parent = [i for i in range(n)]

	def find(self, x):
		if self.parent[x] != x:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, x, y):
		xset = self.find(x)
		yset = self.find(y)
		if xset == yset:
			return
		if self.rank[xset] < self.rank[yset]:
			self.parent[xset] = yset
		elif self.rank[xset] > self.rank[yset]:
			self.parent[yset] = xset
		else:
			self.parent[yset] = xset
			self.rank[xset] = self.rank[xset] + 1

def f(arr, i, j, d, dist):
	if i == j:
		return
	nn = max(arr[i:j])
	for tl in range(i, j):
		if arr[tl] == nn:
			dist[tl] = d
			f(arr, i, tl, d + 1, dist)
			f(arr, tl + 1, j, d + 1, dist)

def ps(n):
	cp = 0
	while n % 2 == 0:
		n = n // 2
		cp += 1
	for ps in range(3, ceil(sqrt(n)) + 1, 2):
		while n % ps == 0:
			n = n // ps
			cp += 1
	if n != 1:
		return False
	return True

def find_gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def factorials(n, r):
	slr = n
	dpr = r
	qlr = 1
	qs = 1
	mod = 10 ** 9 + 7
	for ip in range(n - r + 1, n + 1):
		qlr = qlr * ip % mod
	for ij in range(1, r + 1):
		qs = qs * ij % mod
	ans = qlr * modInverse(qs) % mod
	return ans

def modInverse(b):
	qr = 10 ** 9 + 7
	return pow(b, qr - 2, qr)
tt = [xa ** 3 for xa in range(0, 10 ** 4 + 1)]
qq = set(tt)

def digits(k, rp):
	n = len(k)
	pq = k[::-1]
	jq = ''
	for ij in pq:
		if ij == '1':
			jq += '1'
		elif ij == '2':
			jq += '5'
		elif ij == '4' or ij == '7' or ij == '3' or (ij == '6') or (ij == '9'):
			jq += '-'
		elif ij == '5':
			jq += '2'
		elif ij == '8':
			jq += '8'
		elif ij == '0':
			jq += '0'
	if jq.find('-') != -1:
		return -1
	else:
		jl = int(jq)
		if jl >= rp:
			return -1
		else:
			return jq

def fr(a, b, h, m):
	kl = int(b)
	kl = (kl + 1) % m
	b = '0' * (2 - len(str(kl))) + str(kl)
	if b == '0' * 2:
		kj = (int(a) + 1) % h
		a = '0' * (2 - len(str(kj))) + str(kj)
	return [a, b]
for jj in range(t):
	(h, m) = [int(x) for x in input().strip().split()]
	kq = input().strip()
	hrs = h
	mins = m
	while True:
		if digits(kq[:2], m) != -1 and digits(kq[3:], h) != -1:
			print(kq)
			break
		klp = fr(kq[:2], kq[3:], h, m)
		kq = klp[0] + ':' + klp[1]


l = [0, 1, 2, 5, 8]
le = len(l)
for _ in range(int(input())):
	(a, b) = map(int, input().split())
	s = input()
	hh = ''
	mm = ''
	hh += s[:2]
	mm += s[3:]
	hh = int(hh)
	mm = int(mm)
	f = 0
	temp = [0] * 5
	arr = [0] * 5
	idx = 1
	ht = hh
	while ht >= 1:
		arr[idx] = ht % 10
		ht //= 10
		idx -= 1
	ht = mm
	idx = 3
	while ht >= 1:
		arr[idx] = ht % 10
		idx -= 1
		ht //= 10
	for i in range(0, 4):
		temp[i] = arr[i]
	x = 0
	while 1:
		ff = 1
		for i in arr:
			if i not in l:
				ff = 0
		if ff:
			ans1 = ''
			if arr[3] == 2:
				ans1 += '5'
			elif arr[3] == 5:
				ans1 += '2'
			else:
				ans1 += str(arr[3])
			if arr[2] == 2:
				ans1 += '5'
			elif arr[2] == 5:
				ans1 += '2'
			else:
				ans1 += str(arr[2])
			xx = int(ans1)
			ans2 = ''
			if arr[1] == 2:
				ans2 += '5'
			elif arr[1] == 5:
				ans2 += '2'
			else:
				ans2 += str(arr[1])
			if arr[0] == 2:
				ans2 += '5'
			elif arr[0] == 5:
				ans2 += '2'
			else:
				ans2 += str(arr[0])
			xx1 = int(ans2)
			if xx < a and xx1 < b:
				f = 1
				break
		str1 = '' + str(arr[2]) + str(arr[3])
		num = int(str1)
		num += 1
		if num >= b:
			arr[2] = 0
			arr[3] = 0
			str1 = str(arr[0]) + str(arr[1])
			num = int(str1)
			num += 1
			if num >= a:
				arr[1] = 0
				arr[0] = 0
			else:
				str1 = str(num)
				if len(str1) == 1:
					str1 = '0' + str(num)
				arr[0] = int(str1[0])
				arr[1] = int(str1[1])
		else:
			str1 = str(num)
			if len(str1) == 1:
				str1 = '0' + str(num)
			arr[2] = int(str1[0])
			arr[3] = int(str1[1])
		fff = 1
		for i in range(0, 4):
			if temp[i] != arr[i]:
				fff = 0
		if x and fff:
			break
		x += 1
	if f:
		print(str(arr[0]) + str(arr[1]) + ':' + str(arr[2]) + str(arr[3]))
	else:
		print('00:00')


from collections import Counter

def isValid(ss, s, e):
	d = {'0': '0', '1': '1', '2': '5', '8': '8', '5': '2'}
	nss = ''
	f = 0
	for i in ss:
		if i in d:
			nss += d[i]
		else:
			f = 1
			break
	if f == 1:
		return False
	elif s <= int(nss[::-1]) < e:
		return True
	else:
		return False

def mirror(ss):
	d = {'0': '0', '1': '1', '2': '5', '8': '8', '5': '2'}
	nss = ''
	f = 0
	for i in ss:
		if i in d:
			nss += d[i]
	return nss
for k in range(int(input())):
	(h, m) = map(int, input().split())
	time = input().split(':')
	hh = time[0]
	mm = time[1]
	temp = hh
	tmp = mm
	while isValid(mm, 0, h) == False:
		if isValid(mm, 0, h) == False:
			mm = (int(mm) + 1) % m
			mm = str(mm)
			if len(mm) == 1:
				mm = '0' + mm
			if mm == '00':
				hh = (int(hh) + 1) % h
				hh = str(hh)
				if len(hh) == 1:
					hh = '0' + hh
		else:
			mm = mirror(mm)
	while isValid(hh, 0, m) == False:
		if isValid(hh, 0, m) == False:
			hh = (int(hh) + 1) % h
			hh = str(hh)
			if len(hh) == 1:
				hh = '0' + hh
		else:
			hh = mirror(hh)
	if int(hh) != int(temp):
		mm = '00'
	print(hh + ':' + mm)


d = {1: 1, 2: 5, 5: 2, 8: 8, 0: 0}

def check(x):
	(one, ten) = (x % 10, x // 10)
	if one in d and ten in d:
		return d[one] * 10 + d[ten]
	return float('inf')
for i in range(int(input())):
	(h, m) = list(map(int, input().split()))
	(x, y) = list(map(int, input().split(':')))
	while True:
		if check(x) < m and check(y) < h:
			break
		y += 1
		if y >= m:
			y = 0
			x = (x + 1) % h
	print(str(x).rjust(2, '0') + ':' + str(y).rjust(2, '0'))


number_to_mirror = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}

def is_correct(l, r, h, m):
	(a, b) = (l // 10, l % 10)
	(c, d) = (r // 10, r % 10)
	mirror = []
	for v in [a, b, c, d]:
		if number_to_mirror.get(v) is None:
			return False
		mirror.append(number_to_mirror[v])
	(d, c, b, a) = mirror
	l = a * 10 + b
	r = c * 10 + d
	return l < h and r < m

def main():
	t = int(input())
	result = []
	for _ in range(t):
		(h, m) = map(int, input().split())
		s = input()
		(l, r) = map(int, s.split(':'))
		while not is_correct(l, r, h, m):
			r += 1
			if r >= m:
				r = 0
				l += 1
			if l >= h:
				l = 0
		(a, b) = (l // 10, l % 10)
		(c, d) = (r // 10, r % 10)
		result.append(f'{a}{b}:{c}{d}')
	print('\n'.join(result))
main()


a = int(input())
reflect = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]
for i in range(a):
	(h, m) = map(int, input().split())
	s = input()
	l1 = [h % 10, h // 10]
	l2 = [m % 10, m // 10]
	x = s.index(':')
	s1 = int(s[0:2])
	s2 = int(s[3:])
	glag = 0
	value = s1 * m + s2
	ori = h * m
	cnt = 0
	while glag == 0:
		time = (cnt + value) % ori
		i = time // m
		j = time % m
		cnt += 1
		t1 = str(i)
		t2 = str(j)
		if len(t1) == 1:
			t1 = '0' + t1
		if len(t2) == 1:
			t2 = '0' + t2
		flag = 0
		for i in range(len(t1)):
			if reflect[int(t1[i])] == -1:
				flag = 1
				break
		for i in range(len(t2)):
			if reflect[int(t2[i])] == -1:
				flag = 1
				break
		if flag == 0 and glag == 0:
			tig = reflect[int(t2[1])] * 10 + reflect[int(t2[0])]
			total = tig * m
			rig = reflect[int(t1[1])] * 10 + reflect[int(t1[0])]
			total += rig
			if total >= ori or rig >= m:
				continue
			glag = 1
			print(t1, end='')
			print(':', end='')
			print(t2)


def mirro(n):
	if n == 5:
		return 2
	elif n == 2:
		return 5
	else:
		return n
t = int(input())
ok = [0, 1, 2, 5, 8]
for _ in range(t):
	(h, m) = map(int, input().split())
	ttime = str(input())
	(hnow, mnow) = (int(ttime[0]) * 10 + int(ttime[1]), int(ttime[3]) * 10 + int(ttime[4]))
	while True:
		(h0, h1) = (hnow // 10, hnow % 10)
		(m0, m1) = (mnow // 10, mnow % 10)
		if h0 in ok and h1 in ok and (m0 in ok) and (m1 in ok):
			mh0 = mirro(m1)
			mh1 = mirro(m0)
			mm0 = mirro(h1)
			mm1 = mirro(h0)
			mh = 10 * mh0 + mh1
			mm = 10 * mm0 + mm1
			if mh < h and mm < m:
				minu = m0 * 10 + m1 + 100
				hour = h0 * 10 + h1 + 100
				print(''.join([str(hour)[1:], ':', str(minu)[1:]]))
				break
		mnow += 1
		if mnow == m:
			mnow = 0
			hnow += 1
			if hnow == h:
				hnow = 0


from sys import stdin
input = stdin.readline

def reflect(n):
	a = n // 10
	b = n % 10
	s = 0
	if b == 5:
		s += 20
	elif b == 2:
		s += 50
	else:
		s += b * 10
	if a == 5:
		s += 2
	elif a == 2:
		s += 5
	else:
		s += a
	return s

def next_reflectable(n, m, h):
	for i in range(n, m):
		if set(str(i)).issubset({'0', '1', '2', '5', '8'}) and reflect(i) < h:
			return '0' + str(i) if i < 10 else str(i)
	return '00'
for _ in range(int(input())):
	(h, m) = map(int, input().split())
	s = input().strip()
	(t, k) = s.split(':')
	q1 = next_reflectable(int(t), h, m)
	if q1 == t:
		q2 = next_reflectable(int(k), m, h)
		if q2 == '00' and k != '00':
			q1 = next_reflectable((int(t) + 1) % h, h, m)
		r = q1 + ':' + q2
	else:
		r = q1 + ':00'
	print(r)


ref = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]

def solve(h, m, time):
	h0 = int(time[:2])
	m0 = int(time[3:])
	a = [h0 // 10, h0 % 10, m0 // 10, m0 % 10]
	b = list(map(lambda x: ref[x], a))[::-1]
	while True:
		h1 = 10 * b[0] + b[1]
		m1 = 10 * b[2] + b[3]
		if -1 not in b and h1 < h and (m1 < m):
			return str(a[0]) + str(a[1]) + ':' + str(a[2]) + str(a[3])
		m0 += 1
		if m0 == m:
			m0 = 0
			h0 += 1
			if h0 == h:
				h0 = 0
		a = [h0 // 10, h0 % 10, m0 // 10, m0 % 10]
		b = list(map(lambda x: ref[x], a))[::-1]
import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for i in range(t):
	(h, m) = map(int, input().split())
	time = input()
	print(solve(h, m, time))


N = 100
a = (5, N, N, 2, N, N, 8, N, 0, 1)
R = lambda x=' ': map(int, input().split(x))
(t,) = R()
exec(t * "h,m=R();x,y=R(':');y+=x*m;u=v=w=q=N\nwhile h<=w+q*10or v*10+u>=m:r=f'{y//m%h:02}:{y%m:02}';y+=1;u,v,_,w,q=(a[ord(x)%10]for x in r)\nprint(r)\n")


from heapq import *
from sys import *
from math import *
g = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]

def up(s, n):
	if s[n] == 0:
		s[n] = 1
	elif s[n] == 1:
		s[n] = 2
	elif s[n] == 2:
		s[n] = 5
	elif s[n] == 5:
		s[n] = 8
	elif s[n] == 8:
		if s[n - 1] == 0:
			s[n - 1] = 2
		elif s[n - 1] == 2:
			s[n - 1] = 5
		elif s[n - 1] == 5:
			s[n - 1] = 8
		elif s[n - 1] == 8:
			s[n - 1] == 10
		s[n] = 0

def add(s, h, m):
	up(s, 3)
	if s[2] * 10 + s[3] >= min(m, 88):
		s[2] = 0
		s[3] = 0
		up(s, 1)
		if s[0] * 10 + s[1] >= min(h, 88):
			s[0] = 0
			s[1] = 0

def just(s, h, m):
	global g
	a = s[0] * 10 + s[1]
	b = s[2] * 10 + s[3]
	while True:
		s[0] = int(a / 10)
		s[1] = a % 10
		s[2] = int(b / 10)
		s[3] = b % 10
		c = True
		for i in s:
			if g[i] == -1:
				c = False
		if c == True:
			break
		b += 1
		if b >= m:
			b = 0
			a += 1
			if a >= h:
				a = 0

def chk(s, h, m):
	global g
	ss = s[:]
	for i in range(len(ss)):
		ss[i] = g[ss[i]]
	a = ss[3] * 10 + ss[2]
	b = ss[1] * 10 + ss[0]
	if a < h and b < m:
		return True
	else:
		return False
qn = int(input())
for count in range(qn):
	(h, m) = list(map(int, input().split()))
	s = list(input())
	s.pop(2)
	s = list(map(int, s))
	just(s, h, m)
	while not chk(s, h, m):
		s[3] += 1
		just(s, h, m)
	print(s[0], end='')
	print(s[1], end='')
	print(':', end='')
	print(s[2], end='')
	print(s[3], end='')
	print('')


import sys, os, io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')

def isPrime(x):
	for i in range(2, x):
		if i * i > x:
			break
		if x % i == 0:
			return False
	return True

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def si():
	return input()

def prefix_sum(arr):
	r = [0] * (len(arr) + 1)
	for (i, el) in enumerate(arr):
		r[i + 1] = r[i] + el
	return r

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

def ii():
	return int(input())

def li():
	return list(map(int, input().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')

def power_set(L):
	cardinality = len(L)
	n = 2 ** cardinality
	powerset = []
	for i in range(n):
		a = bin(i)[2:]
		subset = []
		for j in range(len(a)):
			if a[-j - 1] == '1':
				subset.append(L[j])
		powerset.append(subset)
	powerset_orderred = []
	for k in range(cardinality + 1):
		for w in powerset:
			if len(w) == k:
				powerset_orderred.append(w)
	return powerset_orderred

def fastPlrintNextLines(a):
	print('\n'.join(map(str, a)))

def sortByFirstAndSecond(A):
	A = sorted(A, key=lambda x: x[0])
	A = sorted(A, key=lambda x: x[1])
	return list(A)
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def isValid(hh, mm, l, h, m):
	c = hh
	while c:
		x = c % 10
		if l[x] == -1:
			return 0
		c //= 10
	c = mm
	while c:
		x = c % 10
		if l[x] == -1:
			return 0
		c //= 10
	hh = str(hh)
	if len(hh) == 1:
		hh = '0' + hh
	mm = str(mm)
	if len(mm) == 1:
		mm = '0' + mm
	hh = list(hh)
	mm = list(mm)
	hh.reverse()
	mm.reverse()
	hh[0] = str(l[int(hh[0])])
	hh[1] = str(l[int(hh[1])])
	mm[0] = str(l[int(mm[0])])
	mm[1] = str(l[int(mm[1])])
	hh = int(''.join(hh))
	mm = int(''.join(mm))
	if hh < m and mm < h:
		return 1
	return 0

def solve():
	(h, m) = li()
	(H, M) = input().split(':')
	H = int(H)
	M = int(M)
	ans = -1
	l = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]
	f = 0
	ansm = 10000000000000000000000000
	hh = H
	mm = M
	c = 0
	while c <= h * m + 1:
		if isValid(hh, mm, l, h, m) == 1:
			ans = [hh, mm]
			ans[0] = str(ans[0])
			ans[1] = str(ans[1])
			if len(ans[0]) == 1:
				ans[0] = '0' + ans[0]
			if len(ans[1]) == 1:
				ans[1] = '0' + ans[1]
			a = ans[0] + ':' + ans[1]
			print(a)
			return
		mm += 1
		if mm == m:
			mm = 0
			hh += 1
			c += 1
		if hh == h:
			hh = 0
t = 1
t = int(input())
for _ in range(t):
	solve()


def gg(x):
	if x == '0':
		return '0'
	elif x == '1':
		return '1'
	elif x == '2':
		return '5'
	elif x == '5':
		return '2'
	elif x == '8':
		return '8'
	else:
		return '-'

def solve():
	(h, m) = map(int, input().split())
	(s, f) = map(int, input().split(':'))
	for i in range(s, h):
		for j in range(f, m):
			if i != s:
				j = 0
			ss = ''
			ff = ''
			ii = str(i)
			jj = str(j)
			if len(ii) == 1:
				ii = '0' + ii
			if len(jj) == 1:
				jj = '0' + jj
			for c in ii:
				ss += gg(c)
			for c in jj:
				ff += gg(c)
			if ss.count('-') == 0 and ff.count('-') == 0 and (int(ss[::-1]) <= m - 1) and (int(ff[::-1]) <= h - 1):
				print(f'{ii}:{jj}')
				return
	print('00:00')
import math
for _ in range(int(input())):
	solve()


def replaceNthCh(str, n, ch):
	if n >= len(str):
		return str
	return str[0:n] + ch + str[n + 1:len(str)]

def isValidHours(num):
	if num < hoursPerDay:
		return True
	else:
		return False

def isValidMinutes(num):
	if num < minutesPerHour:
		return True
	else:
		return False

def isValidMirroredHours(num):
	hr = format(num, '02d')
	for i in range(len(hr)):
		if hr[i] == '5':
			hr = replaceNthCh(hr, i, '2')
		elif hr[i] == '2':
			hr = replaceNthCh(hr, i, '5')
	mirrored = int(hr[1] + hr[0])
	return isValidMinutes(mirrored)

def isValidMirroredMinutes(num):
	mn = format(num, '02d')
	for i in range(len(mn)):
		if mn[i] == '5':
			mn = replaceNthCh(mn, i, '2')
		elif mn[i] == '2':
			mn = replaceNthCh(mn, i, '5')
	mirrored = int(mn[1] + mn[0])
	return isValidHours(mirrored)

def isValidTime(hr, mn):
	return isValidHours(hr) and isValidMinutes(mn)

def isValidMirroredTime(hr, mn):
	return isValidMirroredHours(hr) and isValidMirroredMinutes(mn)

def timeToNum(hr, mn):
	return int(format(hr, '02d') + format(mn, '02d'))
validMirroredNums = [0, 1, 2, 5, 8]
mirroredNums = [0, 1, 5, 2, 8]
n = int(input())
for _ in range(n):
	(hoursPerDay, minutesPerHour) = list(map(int, input().split()))
	(hoursNow, minutesNow) = list(map(int, input().split(':')))
	validTime = []
	for hr1st in validMirroredNums:
		for hr2nd in validMirroredNums:
			for mn1st in validMirroredNums:
				for mn2nd in validMirroredNums:
					hr = hr1st * 10 + hr2nd
					mn = mn1st * 10 + mn2nd
					if isValidTime(hr, mn):
						if isValidMirroredTime(hr, mn):
							validTime.append(timeToNum(hr, mn))
	nowNum = timeToNum(hoursNow, minutesNow)
	result = -1
	for i in range(len(validTime)):
		if nowNum <= validTime[i]:
			result = validTime[i]
			break
	if result == -1:
		result = validTime[0]
	result = format(result, '04d')
	print(result[0:2] + ':' + result[2:4])


from itertools import product
from bisect import bisect_left as bl

def espelhaletra(string):
	return string.replace('5', '-').replace('2', '5').replace('-', '2')

def valida(prox, maxhora):
	normal = prox[:2] <= maxhora[:2] and prox[2:] <= maxhora[2:]
	revers = espelhaletra(prox[:1:-1]) <= maxhora[:2] and espelhaletra(prox[1::-1]) <= maxhora[2:]
	return normal and revers
combin = [''.join(c) for c in product('01258', '01258', '01258', '01258')]
lenCombin = len(combin)
for _ in range(int(input())):
	maxhora = [int(x) for x in input().split()]
	maxhora[0] -= 1
	maxhora[1] -= 1
	maxhora = ''.join((str(x).zfill(2) for x in maxhora))
	momento = input().replace(':', '')
	iMax = bl(combin, maxhora)
	iProx = bl(combin, momento)
	if iMax >= lenCombin:
		iMax = lenCombin - 1
	if iProx >= lenCombin:
		iProx = 0
	while not valida(combin[iProx], maxhora):
		iProx += 1
		if iProx > iMax:
			break
	print(combin[0][:2] + ':' + combin[0][2:] if iProx > iMax else combin[iProx][:2] + ':' + combin[iProx][2:])


import sys, io, os
BUFSIZE = 8192

class FastIO(io.IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = io.BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(io.IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
MOD = 1000000007

def si():
	return input()

def ii():
	return int(input())

def li():
	return list(map(int, input().split()))

def mi():
	return map(int, input().split())

def sout(v):
	print(v, end=' ')

def d2b(n):
	return bin(n).replace('0b', '')

def twod(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def vow():
	return ['a', 'e', 'i', 'o', 'u']

def let():
	return [chr(i) for i in range(97, 123)]

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def ispow2(x):
	return x and (not x & x - 1)

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return list(factors)

def binary_search(arr, low, high, x):
	if high >= low:
		mid = (high + low) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] > x:
			return binary_search(arr, low, mid - 1, x)
		else:
			return binary_search(arr, mid + 1, high, x)
	else:
		return -1

def isvalid(ref, h, m, HH, MM):
	if h < 10:
		hour = '0' + str(h)
	else:
		hour = str(h)
	if m < 10:
		mins = '0' + str(m)
	else:
		mins = str(m)
	ref_hr = ref[hour[1]] + ref[hour[0]]
	ref_min = ref[mins[1]] + ref[mins[0]]
	if int(ref_min[0]) * 10 + int(ref_min[1]) < HH and int(ref_hr[0]) * 10 + int(ref_hr[1]) < MM:
		return hour + ':' + mins
	return False
t = ii()
while t:
	t -= 1
	(HH, MM) = mi()
	a = si()
	exc = [3, 4, 6, 7, 9]
	reflection = {'1': '1', '2': '5', '5': '2', '8': '8', '0': '0'}
	if a[0] == '0':
		hour = int(a[1])
	else:
		hour = int(a[0]) * 10 + int(a[1])
	if a[3] == '0':
		mins = int(a[4])
	else:
		mins = int(a[3]) * 10 + int(a[4])
	ans = '00:00'
	f = 0
	for h in range(hour, HH):
		if h == hour:
			x = mins
		else:
			x = 0
		if h % 10 in exc:
			continue
		if h // 10 % 10 in exc:
			continue
		for m in range(x, MM):
			if m % 10 in exc:
				continue
			if m // 10 % 10 in exc:
				continue
			b = isvalid(reflection, h, m, HH, MM)
			if b:
				f = 1
				ans = b
				break
		if f == 1:
			break
	print(ans)


def do():
	conv = dict()
	conv['0'] = '0'
	conv['1'] = '1'
	conv['2'] = '5'
	conv['3'] = 'xxxxxx'
	conv['4'] = 'xxxxxx'
	conv['5'] = '2'
	conv['6'] = 'xxxxxx'
	conv['7'] = 'xxxxxx'
	conv['8'] = '8'
	conv['9'] = 'xxxxxx'

	def isitok(curtime):
		curtime %= maxtime
		(h, m) = (curtime // maxm, curtime % maxm)
		hstr = '{:02}'.format(h)
		mstr = '{:02}'.format(m)
		newm = conv[hstr[1]] + conv[hstr[0]]
		newh = conv[mstr[1]] + conv[mstr[0]]
		if newm.find('x') != -1 or newh.find('x') != -1:
			return False
		if int(newh) >= maxh or int(newm) >= maxm:
			return False
		return True
	(maxh, maxm) = map(int, input().split())
	s = input().split(':')
	(h, m) = (int(s[0]), int(s[1]))
	curtime = maxm * h + m
	maxtime = maxh * maxm
	while True:
		if isitok(curtime):
			(h, m) = (curtime // maxm, curtime % maxm)
			print('{:02}'.format(h) + ':' + '{:02}'.format(m))
			break
		curtime += 1
		curtime %= maxtime
q = int(input())
for _ in range(q):
	do()


c_digits = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]

def normalise(string):
	n = len(string)
	if n == 5:
		return string
	if n == 3:
		return '0' + string[0] + ':' + '0' + string[2]
	if n == 4:
		if string[2] == ':':
			return string[0:3] + '0' + string[3]
		else:
			return '0' + string

def correct(string, h, m):
	string = normalise(string)
	a = int(string[0])
	b = int(string[1])
	c = int(string[3])
	d = int(string[4])
	if c_digits[a] == -1 or c_digits[b] == -1 or c_digits[c] == -1 or (c_digits[d] == -1):
		return False
	a_dash = c_digits[d]
	b_dash = c_digits[c]
	c_dash = c_digits[b]
	d_dash = c_digits[a]
	hours = int(str(a_dash) + str(b_dash))
	minutes = int(str(c_dash) + str(d_dash))
	if hours <= h - 1 and minutes <= m - 1:
		return True
	else:
		return False

def answer(string, h, m):
	hours = int(string[0:2])
	minutes = int(string[3:5])
	for j in range(minutes, m):
		str_dash = str(hours) + ':' + str(j)
		if correct(str_dash, h, m):
			return normalise(str_dash)
	for i in range(hours + 1, h):
		for j in range(m):
			str_dash = str(i) + ':' + str(j)
			if correct(str_dash, h, m):
				return normalise(str_dash)
	return '00:00'
t = int(input())
for i in range(t):
	[h, m] = list(map(int, input().split()))
	s = input()
	print(answer(s, h, m))


revert = {'0': '0', '1': '1', '2': '5', '3': '_', '4': '_', '5': '2', '6': '_', '7': '_', '8': '8', '9': '_'}

def rev(s):
	return revert[s[1]] + revert[s[0]]
for _ in range(int(input())):
	(H, M) = tuple(map(int, input().split()))
	(h, m) = tuple(map(int, input().split(':')))
	t = h * M + m
	while True:
		x = str(t // M % H).zfill(2)
		y = str(t % M).zfill(2)
		a = rev(str(y))
		b = rev(str(x))
		if not a.count('_') and (not b.count('_')) and (0 <= int(a) < H) and (0 <= int(b) < M):
			print(f'{x}:{y}')
			break
		t += 1


import math
import sys
from collections import *
import itertools

def cint():
	return list(map(int, sys.stdin.readline().strip().split()))

def cstr():
	return list(map(str, input().split(' ')))

def solve(t):
	(maxhour, maxmin) = cstr()
	s = input()
	s = s.replace(':', '')
	(h1, h2, m1, m2) = [i for i in s]
	hour = h1 + h2
	min = m1 + m2
	dct = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'}
	vlst = ['0', '1', '2', '5', '8']
	lst = []

	def perm():
		templst = [p for p in itertools.product(vlst, repeat=4)]
		for item in templst:
			(h1, h2, m1, m2) = item
			if int(h1 + h2) < int(maxhour) and int(m1 + m2) < int(maxmin):
				newhour = dct.get(m2) + dct.get(m1)
				newmin = dct.get(h2) + dct.get(h1)
				if int(newhour) < int(maxhour) and int(newmin) < int(maxmin):
					lst.append([h1 + h2, m1 + m2])
	if h1 in vlst and h2 in vlst and (m1 in vlst) and (m2 in vlst):
		newhour = dct.get(m2) + dct.get(m1)
		newmin = dct.get(h2) + dct.get(h1)
		if int(newhour) < int(maxhour) and int(newmin) < int(maxmin):
			print(f'{hour}:{min}')
			return
		else:
			perm()
	else:
		perm()
	for (nh, nm) in lst:
		if nh > hour or (nh == hour and nm > min):
			print(f'{nh}:{nm}')
			return
	print('00:00')
t = int(input())
for i in range(1, t + 1):
	solve(i)


T = int(input())
for _ in range(T):
	(H, M) = map(int, input().split())
	S = input()
	start = int(S[0:2]) * M
	start += int(S[3:5])
	goal = H * M
	cond = []
	for now in range(start, goal):
		now_hour = now // M
		now_min = now % M
		clock = str(now_hour).zfill(2) + str(now_min).zfill(2)
		isOK = True
		T = ''
		for i in range(3, -1, -1):
			st = clock[i]
			if st in ['0', '1', '8']:
				T += st
			elif st == '2':
				T += '5'
			elif st == '5':
				T += '2'
			else:
				isOK = False
				break
		ans = '00:00'
		if isOK:
			mirror = int(T[0:2]) * M
			mirror += int(T[2:4])
			if mirror >= goal:
				continue
			elif int(T[0:2]) >= H or int(T[2:4]) >= M:
				continue
			else:
				ans = clock[0:2] + ':' + clock[2:4]
				break
	print(ans)