#include<iostream>
#include<cstdio>
using namespace std;
int T;
string s;
int h,m;
int x,y;
int fl[10]={0,1,5,-1,-1,2,-1,-1,8,-1};
void print(int x,int y)
{
    cout<<x/10<<x%10<<":"<<y/10<<y%10<<endl;
}
void add(int &x,int &y)
{
    y++;
    if(y==m)  y=0,x++;
    if(x==h)  x=0;
}
int op(int x,int y)
{
    int a=x/10,b=x%10;
    int c=y/10,d=y%10;
    if(fl[a]==-1 || fl[b]==-1 || fl[c]==-1 || fl[d]==-1)  return 0;
    x=fl[d]*10+fl[c];
    y=fl[b]*10+fl[a];
    if(x>=h || y>=m)  return 0;
    return 1; 
}
int main()
{
    cin>>T;
    while(T--)
    {
        cin>>h>>m>>s;
        x=(s[0]-'0')*10+(s[1]-'0');
        y=(s[3]-'0')*10+(s[4]-'0');
        while(op(x,y)==0)  add(x,y);
        print(x,y);
    }
}