专栏文章
题解:P14497 [NCPC 2025] Crochet Competition
P14497题解参与者 1已保存评论 0
文章操作
快速查看文章及其快照的属性,并进行相关操作。
- 当前评论
- 0 条
- 当前快照
- 1 份
- 快照标识符
- @min6moif
- 此快照首次捕获于
- 2025/12/01 21:25 3 个月前
- 此快照最后确认于
- 2025/12/01 21:25 3 个月前
题意
这道题要求我们计算比赛的总时长,给定开始时间和结束时间,需要以天、小时、分钟的形式表示结果,并遵循格式要求输出。
思路
- 将输入的时间转换为可计算的数值形式(总分钟数)。
- 计算两个时间点之间的差值,注意处理跨周的情况。
- 将总分钟数转换为天、小时、分钟的形式。
- 按照要求的格式输出结果。
代码
CPP#include<bits/stdc++.h>
using namespace std;
// 将星期缩写转换为数字(0-6)
int get_weekday(const string& w) {
static unordered_map<string, int> weekday_map = {
{"Mon", 0}, {"Tue", 1}, {"Wed", 2}, {"Thu", 3},
{"Fri", 4}, {"Sat", 5}, {"Sun", 6}
};
return weekday_map[w];
}
// 将时间转换为总分钟数(从周一00:00开始计算)
int time_to_minutes(const string& weekday, int hour, int minute) {
int wd = get_weekday(weekday);
return wd * 24 * 60 + hour * 60 + minute;
}
// 解析时间字符串
void parse_time(const string& s, string& weekday, int& hour, int& minute) {
weekday = s.substr(0, 3);
hour = stoi(s.substr(4, 2));
minute = stoi(s.substr(7, 2));
}
int main() {
string start_str, end_str;
getline(cin, start_str);
getline(cin, end_str);
string start_weekday, end_weekday;
int start_hour, start_minute, end_hour, end_minute;
parse_time(start_str, start_weekday, start_hour, start_minute);
parse_time(end_str, end_weekday, end_hour, end_minute);
int start_total = time_to_minutes(start_weekday, start_hour, start_minute);
int end_total = time_to_minutes(end_weekday, end_hour, end_minute);
const int week_minutes = 7 * 24 * 60; // 一周的总分钟数
int diff = end_total - start_total;
// 处理跨周的情况
if (diff <= 0) {
diff += week_minutes;
}
// 计算天、小时、分钟
int days = diff / (24 * 60);
diff %= (24 * 60);
int hours = diff / 60;
int minutes = diff % 60;
// 收集非零部分
vector<pair<int, string>> parts;
if (days > 0) {
parts.emplace_back(days, days == 1 ? "day" : "days");
}
if (hours > 0) {
parts.emplace_back(hours, hours == 1 ? "hour" : "hours");
}
if (minutes > 0) {
parts.emplace_back(minutes, minutes == 1 ? "minute" : "minutes");
}
// 输出结果
if (parts.empty()) {
// 这种情况只有当diff为0时才会发生,根据题目要求输出一周
cout << "7 days" << endl;
} else if (parts.size() == 1) {
cout << parts[0].first << " " << parts[0].second << endl;
} else if (parts.size() == 2) {
cout << parts[0].first << " " << parts[0].second << " and "
<< parts[1].first << " " << parts[1].second << endl;
} else { // parts.size() == 3
cout << parts[0].first << " " << parts[0].second << ", "
<< parts[1].first << " " << parts[1].second << ", "
<< parts[2].first << " " << parts[2].second << endl;
}
return 0;
}
相关推荐
评论
共 0 条评论,欢迎与作者交流。
正在加载评论...