#include #include #include #include #include #include #include #include #include using namespace std; bool can(int x) { if (x == 0 || x == 1 || x == 2 || x == 5 || x == 8) { return 1; } else return 0; } unordered_map _hash; int main() { _hash[2] = 5; _hash[0] = 0; _hash[5] = 2; _hash[1] = 1; _hash[8] = 8; int T; scanf("%d", &T); while (T--) { int h, m; scanf("%d%d", &h, &m); int t1, t2; scanf("%d:%d", &t1, &t2); bool b0 = can(t1 % 10) && can(t1 / 10) && can(t2 % 10) && can(t2 / 10); if (b0) { int newt1 = _hash[(t2 / 10)] + _hash[(t2 % 10)] * 10; int newt2 = _hash[(t1 / 10)] + _hash[(t1 % 10)] * 10; bool b2 = newt1 < h && newt2 < m; if (b2) { printf("%02d:%02d\n", t1, t2); } else { while (1) { t2++; t1 = (t1 + t2 / m) % h; t2 %= m; bool b1 = can(t1 % 10) && can(t1 / 10) && can(t2 % 10) && can(t2 / 10); if (b1) { int newt1 = _hash[(t2 / 10)] + _hash[(t2 % 10)] * 10; int newt2 = _hash[(t1 / 10)] + _hash[(t1 % 10)] * 10; bool b2 = newt1 < h && newt2 < m; if (b2) { printf("%02d:%02d\n", t1, t2); break; } } } } } else { while (1) { t2++; t1 = (t1 + t2 / m) % h; t2 %= m; bool b1 = can(t1 % 10) && can(t1 / 10) && can(t2 % 10) && can(t2 / 10); if (b1) { int newt1 = _hash[(t2 / 10)] + _hash[(t2 % 10)] * 10; int newt2 = _hash[(t1 / 10)] + _hash[(t1 % 10)] * 10; bool b2 = newt1 < h && newt2 < m; if (b2) { printf("%02d:%02d\n", t1, t2); break; } } } } } return 0; }