#include <bits/stdc++.h>

using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long tt;
  cin >> tt;
  vector<long long> mmm(10);
  mmm[0] = 0;
  mmm[1] = 1;
  mmm[2] = 5;
  mmm[3] = -1;
  mmm[4] = -1;
  mmm[5] = 2;
  mmm[6] = -1;
  mmm[7] = -1;
  mmm[8] = 8;
  mmm[9] = -1;
  auto Check = [&](long long x) {
    return (mmm[x/10] != -1 && mmm[x%10] != -1);
  };
  while (tt--) {
    long long h, m;
    string s;
    cin >> h >> m >> s;
    // s HH:MM
    long long hh = 10*(s[0] - '0') + (s[1] - '0');
    long long mm = 10*(s[3] - '0') + (s[4] - '0');
    auto Cost = [&](long long xx, long long yy) { // xx:yy is after hh:mm
      long long cost = 0;
      if (xx == hh) {
        if (yy >= mm) {
          cost = yy - mm;
        } else {
          cost = h*m + yy - mm;
        }
      }
      if (xx > hh) {
        cost = (xx - hh)*m + yy-mm;
      }
      if (xx < hh) {
        cost = ((xx+h-hh)%h)*m + yy-mm;
      }
      return cost;
    };
    long long ans = 1e9;
    long long ans_hh = 0, ans_mm = 0;
    for (long long i = 0; i < h; i++) {
      for (long long j = 0; j < m; j++) {
        if (Check(i) && Check(j)) {
          long long ir = 10*(mmm[i%10]) + mmm[i/10];
          long long jr = 10*(mmm[j%10]) + mmm[j/10];
          if (ir >= m || jr >= h) continue;
          long long cost = Cost(i, j);
          if (cost < ans) {
            ans_hh = i;
            ans_mm = j;
            ans = cost;
          }
        }
      }
    }
    cout << (ans_hh < 10 ? "0" : "");
    cout << ans_hh << ":";
    cout << (ans_mm < 10 ? "0" : "");
    cout << ans_mm << "\n";
  }
  return 0;
}
// go through problem examples
// for A, B: local structure, brute force
// sums, multiplication -> long long
// lcm, gcd -> prime factorization -> first figure for one factor
// expectation, count -> sumation order
// max -> greedy, binsearch, dp
// bit operations -> figure of single bits
