本文共 3139 字,大约阅读时间需要 10 分钟。
镜像时间问题的解决方案
要解决这个问题,我们需要找到从当前时间开始,经过多少分钟后,时间会变成镜像时间。镜像时间是指将时间的每一位数字反转后,得到一个正确的时间。例如,05:11翻转后变成11:20,这是一个有效的时间。
步骤解释:
检查数字是否允许镜像翻转:
镜像翻转数字:
处理输入时间:
验证镜像时间的有效性:
代码实现:
#include#include #include using namespace std;bool ok(int x) { if (x < 10) { return (x == 0 || x == 1 || x == 2 || x == 5 || x == 8); } else if (x == 100) { return true; } else { int a = x / 10, b = x % 10; bool flag = (a == 0 || a == 1 || a == 2 || a == 5 || a == 8); bool b_flag = (b == 0 || b == 1 || b == 2 || b == 5 || b == 8); return flag && b_flag; }}int fi(int x) { if (x == 0 || x == 1 || x == 8) return x; if (x == 2) return 5; if (x == 5) return 2; return 0; // Should never reach here if input is correct}bool check(int a, int b) { if (!ok(a) || !ok(b)) return false; int x, y; if (b == 100) x = 1; else { int b_digits[2] = {b % 10, b / 10}; x = fi(b_digits[1]) * 10 + fi(b_digits[0]); } if (a == 100) y = 1; else { int a_digits[2] = {a % 10, a / 10}; y = fi(a_digits[1]) * 10 + fi(a_digits[0]); } bool h_ok = (y <= h) && (x >= 0); bool m_ok = (x <= m); return h_ok && m_ok;}int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t, h, m, x, y; read(t); while (t--) { read(h, m); int current_h = h, current_m = m; int found = false; for (int i = 0; i <= 1440; ++i) { // 最大24小时后的时间 int current_h_new = current_h, current_m_new = current_m + i; if (current_m_new >= 60) { current_h_new++; current_m_new -= 60; } if (current_h_new > 23) { current_h_new -= 24; current_m_new += 60; } if (current_m_new < 0) { current_h_new--; current_m_new += 60; } if (!ok(current_h_new) || !ok(current_m_new)) continue; if (check(current_m_new, current_h_new)) { found = true; break; } } if (found) { int total = 0; for (int j = 0; j < 1440; ++j) { int new_h = h, new_m = m + j; if (new_m >= 60) { new_h++; new_m -= 60; } if (new_h > 23) { new_h -= 24; new_m += 60; } if (new_m < 0) { new_h--; new_m += 60; } if (!ok(new_h) || !ok(new_m)) continue; if (check(new_m, new_h)) { total = j; break; } } cout << total << endl; } else { cout << -1 << endl; } } return 0;}
代码解释:
这个解决方案确保了代码的高效性和正确性,能够在合理的时间内处理所有测试用例。
转载地址:http://vxdj.baihongyu.com/