题目描述:
警察在侦破一个案件时,得到了线人给出的可能犯罪时间,形如 “HH:MM” 表示的时刻。根据警察和线人的约定,为了隐蔽,该时间是修改过的,解密规则为:利用当前出现过的数字,构造下一个距离当前时间最近的时刻,则该时间为可能的犯罪时间。每个出现的数字都可以被无限次使用。
输入描述:
形如 HH:SS 的字符串,表示原始输入
输出描述:
形如 HH:SS 的字符串,表示推理出来的犯罪时间
特别注意事项:
1. 可以保证线人给定的字符串一定是合法的。例如,“01:35” 和 “11:08” 是合法的,“1:35” 和 “11:8” 是不合法的。
2. 最近的时刻有可能在第二天。
示例1:
输入
18:52
输出
18:55
说明:利用数字 1, 8, 5, 2 构造出来的最近时刻是 18:55,是 3 分钟之后。结果不是 18:51,因为这个时刻是 23 小时 59 分钟之后。
示例2:
输入
23:59
输出
22:22
说明:利用数字 2, 3, 5, 9 构造出来的最近时刻是 22:22。 答案一定是第二天的某一时刻,所以选择可构造的最小时刻为犯罪时间。
C++源码:
#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <cstdlib>
#include <iostream>
using namespace std;
// 检查给定的时间是否合法(即小时小于24,分钟小于60)
bool chcekTime(vector<int>& timeL) {
return timeL[0] < 24 && timeL[1] < 60;
}
// 计算两个时间之间的分钟差
int cal(vector<int>& a, vector<int>& b) {
if (a == b) {
int temp = 24 * 60;
return temp;
}
int timeDiff[] = { b[0] - a[0], b[1] - a[1] };
if (timeDiff[1] < 0) {
timeDiff[0]--;
timeDiff[1] += 60;
}
if (timeDiff[0] < 0) {
timeDiff[0] += 24;
}
int diff = timeDiff[0] * 60 + timeDiff[1];
return diff;
}
// 深度优先搜索,尝试所有可能的时间组合
void dfs(vector<int>& temp, int flag, const set<int>& intTime, vector<int>& last, vector<int>& real) {
if (flag == 4) {
if (chcekTime(temp) && cal(last, temp) < cal(last, real)) {
real = temp;
}
return;
}
for (int i : intTime) {
vector<int> begin = temp;
if (flag == 0) {
temp[0] = temp[0] + i * 10;
}
else if (flag == 1) {
temp[0] = temp[0] + i;
}
else if (flag == 2) {
temp[1] = temp[1] + i * 10;
}
else {
temp[1] = temp[1] + i;
}
dfs(temp, flag + 1, intTime, last, real);
temp = begin;
}
}
void getRealTime(string timeStr, set<int>& intTime) {
vector<int> last(2);
// 将字符串形式的时间转换为整数对
last[0] = (timeStr[0] - '0') * 10 + (timeStr[1] - '0');
last[1] = (timeStr[3] - '0') * 10 + (timeStr[4] - '0');
vector<int> real = last;
vector<int> temp = { 0, 0 };
int flag = 0;
dfs(temp, flag, intTime, last, real);
// 打印时间,格式为HH:MM
printf("%02d:%02d\n", real[0], real[1]);
}
int main() {
string timeStr;
getline(cin, timeStr); // 读入时间
set<int> intTime;
// 将时间字符串转换为整数集合
for (char x : timeStr) {
if (x != ':') {
intTime.insert(x - '0');
}
}
getRealTime(timeStr, intTime);
system("pause");
return 0;
}