#include <iostream> #include <string> #include <vector> #include <algorithm> #include <climits> using namespace std; const int MAX_HOUR = 23; const int MAX_MINUTE = 59; // 验证时间是否有效 bool isValidTime(const string& time) { if (time.size() != 4) return false; int hour = stoi(time.substr(0, 2)); int minute = stoi(time.substr(2, 2)); return hour >= 0 && hour <= MAX_HOUR && minute >= 0 && minute <= MAX_MINUTE; } // 比较两个时间,返回true如果time1 < time2 bool isEarlier(const string& time1, const string& time2) { return time1 < time2; // 字符串比较可以直接比较时间 } // 计算时间差(分钟) int timeDiff(const string& s1, const string& s2) { int h1 = stoi(s1.substr(0, 2)); int m1 = stoi(s1.substr(2, 2)); int h2 = stoi(s2.substr(0, 2)); int m2 = stoi(s2.substr(2, 2)); return (h2 - h1) * 60 + (m2 - m1); } // 生成所有可能的时间组合 void generateTimes(const string& pattern, vector<string>& result, int index = 0, string current = "") { if (index == 4) { if (isValidTime(current)) { result.push_back(current); } return; } if (pattern[index] == '?') { for (char c = '0'; c <= '9'; c++) { generateTimes(pattern, result, index + 1, current + c); } } else { generateTimes(pattern, result, index + 1, current + pattern[index]); } } int main() { string t1, t2; getline(cin, t1); getline(cin, t2); // 移除冒号 t1.erase(remove(t1.begin(), t1.end(), ':'), t1.end()); t2.erase(remove(t2.begin(), t2.end(), ':'), t2.end()); // 生成所有可能的时间组合 vector<string> times1, times2; generateTimes(t1, times1); generateTimes(t2, times2); if (times1.empty() || times2.empty()) { cout << "Invalid time format" << endl; return 0; } // 计算满足s1 < s2的最小和最大时间差 int min_diff = INT_MAX; int max_diff = INT_MIN; bool found = false; for (const auto& time1 : times1) { for (const auto& time2 : times2) { if (isEarlier(time1, time2)) { int diff = timeDiff(time1, time2); min_diff = min(min_diff, diff); max_diff = max(max_diff, diff); found = true; } } } if (!found) { // cout << "No valid time pairs found (s1 must be earlier than s2)" << endl; } else { cout << min_diff << " " << max_diff << endl; } return 0; }
去:,转换?生成字符串,遍历计算结果