
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int mod = 1e9+7;
#define vi vector<int>
#define pb push_back
#define ff first
#define ss second
#define pi pair<int,int>
#define all(v) (v).begin(),(v).end()
#define mk(arr,n,type)  type *arr=new type[n];
#define rrep(i, n) for(int i=n-1;i>=0;i--)
#define rep(i,n) for(int i=0;i<n;i++)
#define repm(i,a,b) for(int i=a ; i<b ; i++)
int gcd(int a , int b){
  if(b==0) return a;

  return gcd(b,a%b);
}

void cp(){
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);

  #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n";
  #endif
}

int arr[10];
 
int h,m;
bool check(int a, int b){
  if(arr[a%10] == -1 || arr[a/10] == -1 || arr[b%10] == -1 || arr[b/10] == -1){
    return 0;
  }
  
  int x = arr[b%10] * 10 + arr[b/10];
  int y = arr[a%10] * 10 + arr[a/10];
  
  if(x < h && y < m){
    return 1;
  }
  else{
    return 0;
  }
  
}
 
void solve(){
  
  memset(arr,-1,sizeof(arr));
  arr[0] = 0;
  arr[1] = 1;
  arr[2] = 5;
  arr[5] = 2;
  arr[8] = 8;
  
  cin >> h >> m;
  string t;
  cin >> t;
  
  int a = (t[0] - '0') * 10 + t[1] - '0';
  int b = (t[3] - '0') * 10 + t[4] - '0';
  
  
  while(!check(a,b)){
    b++;
    if(b == m) a++;
    b %= m;
    a %= h;
  }
  
  printf("%02d:",a);
  printf("%02d\n",b);
  
}

int32_t main(){
  cp();
  int t = 1;
  cin>>t;

  while(t--)
    solve();

    return 0;
}


