#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<stack>
using namespace std;

inline bool read(int &num)
{
    char in;bool IsN=false;in=getchar();
    if(in==EOF) return false;
    while(in!='-'&&(in<'0'||in>'9')) in=getchar();
    if(in=='-'){ IsN=true;num=0;} else num=in-'0';
    while(in=getchar(),in>='0'&&in<='9'){num*=10,num+=in-'0';}
	if(IsN) num=-num; return true;
}
int gcd(int m, int n)
{ return n? gcd(n, m%n) : m;}

//map<int,int>oxy;
int oxy[20]={0,1,5,-1,-1,2,-1,-1,8,-1};
int h,m;

int panduan(int x,int y)
{
	int a=x/10;
	int b=x%10;
	int c=y/10;
	int d=y%10;
	if(oxy[a]==-1||oxy[b]==-1||oxy[c]==-1||oxy[d]==-1) return 0;
	x=oxy[d]*10+oxy[c];
	y=oxy[b]*10+oxy[a];
	//cout<<"x="<<x<<" y="<<y<<endl;
	if(x<h&&y<m) return 1;
	else return 0;
}
int main( )
{
	//cout<<oxy[2]<<" "<<oxy[9]<<" "<<oxy[8]<<endl;
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d",&h,&m);
		char a[10];
		cin>>a;
		a[2]=a[3];
		a[3]=a[4];
		int haha[6],xixi[6];
		int ok=0;
		int h1=0;int m1=0;
		int h2=0;int m2=0;
		for(int i=1;i<=4;i++)
		{
			haha[i]=a[i-1]-'0';
			xixi[i]=oxy[haha[i]];
			if(xixi[i]==-1) ok++;
		}
		h1=haha[1]*10+haha[2];
		m1=haha[3]*10+haha[4];
		h2=xixi[4]*10+xixi[3];
		m2=xixi[2]*10+xixi[1];
		//cout<<"h1="<<h1<<" m1="<<m1<<" h2="<<h2<<" m2="<<m2<<endl;
		if(h2>=h||m2>=m) ok++;
		if(ok==0) 
		{
			if(h1<10) cout<<"0";
					cout<<h1<<":";
					if(m1<10) cout<<"0";
					cout<<m1<<endl;
		}
		else
		{
			
			//int ans=1;
			int mm1=m1,mm2=m1;
			int hh1=h1,hh2=h1;
			while(1)
			{
				mm1++;
				if(mm1>=m) hh1++,mm1=0;
				if(hh1>=h) hh1=0;
				if(panduan(hh1,mm1)) 
				{
					if(hh1<10) cout<<"0";
					cout<<hh1<<":";
					if(mm1<10) cout<<"0";
					cout<<mm1<<endl;
					break;
				}
			
			}
			
			
		}
	
	}
	return 0;
}
