#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <string>
#include <random>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdio>
#include <numeric>
#include <iostream>
#include <algorithm>
#include <functional>
#include <unordered_map>
#include <unordered_set>
#define sca(aa) scanf("%d",&aa)
#define scal(aa) scanf("%lld",&aa)
#define lb(x) (x&-x)
#define mid ((s+e)>>1)
//#define int LL
#define ls (p<<1)
#define rs (p<<1|1)
//#define P(x) ((x)*(x))
#define lson ls,s,mid
#define rson rs,mid+1,e
#define IT set<node>::iterator
//#define getchar()(p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int inf = INT_MAX;
const int N = 2e5 + 100;
const LL MOD = 998244353;
const double eps = 1e-8;
const ull strmod = 212370440130137957ll;//ll11
const int strp = 233;
//char buf[1 << 21], * p1 = buf, * p2 = buf;
inline LL read() {
	char ch = getchar(); LL x = 0, f = 1;
	while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
	while ('0' <= ch && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
	return x * f;
}
int p[10] = { 0,1,5,-1,-1,2,-1,-1,8,-1 };
int l, r;
int H, M, h, m;
inline bool bad(int x) { return p[x % 10] == -1 || p[x / 10] == -1; }
inline int rev(int x) { return p[x % 10] * 10 + p[x / 10]; }
void solve()
{
	int x = -1, y = -1;
	for (int i = 0; i < H; i++)
		for (int j = 0; j < M; j++)
			if (!bad(i) && !bad(j) && rev(i) < M && rev(j) < H)
			{
				if (x == -1)
					x = i, y = j;
				if (i > h || (i == h && j >= m))
				{
					printf("%02d:%02d\n", i, j);
					return;
				}
			}
	printf("%02d:%02d\n", x, y);
	return;
}
int main() {
	int T;
	cin >> T;
	while (T--)
	{
		
		cin >> H >> M;
		bool fg = 0;
		scanf("%d:%d", &h, &m);
		solve();
				

	}
	return 0;
}