洛谷B3847题"当天的第几秒"是一道典型的日期时间处理题目,主要考察选手对时间计算和基础编程能力的掌握。题目要求给定一个24小时制的时间(时:分:秒),计算该时间距离当天00:00:00已经过去了多少秒。
这道题看似简单,但实际包含了几个关键考察点:
标准输入格式为"HH:MM:SS",其中:
输出要求为一个整数,表示从午夜到该时刻的总秒数。例如:
C++中处理带分隔符的时间字符串,常见有以下几种方法:
cpp复制int h, m, s;
scanf("%d:%d:%d", &h, &m, &s);
cpp复制string time;
cin >> time;
size_t pos1 = time.find(':');
size_t pos2 = time.find(':', pos1+1);
int h = stoi(time.substr(0, pos1));
int m = stoi(time.substr(pos1+1, pos2-pos1-1));
int s = stoi(time.substr(pos2+1));
cpp复制char c;
int h, m, s;
cin >> h >> c >> m >> c >> s;
提示:算法竞赛中推荐使用scanf方案,因其效率最高且代码简洁。实际工程中则更推荐使用字符串分割方案,可读性更好。
将时、分、秒转换为总秒数的数学表达式为:
code复制总秒数 = 小时 × 3600 + 分钟 × 60 + 秒
需要注意的边界情况:
cpp复制#include <cstdio>
int main() {
int h, m, s;
scanf("%d:%d:%d", &h, &m, &s);
printf("%d\n", h * 3600 + m * 60 + s);
return 0;
}
代码解析:
在算法竞赛中,当数据量较大时(如本题可能有1e5组测试数据),IO会成为性能瓶颈。可以采用以下优化:
cpp复制ios::sync_with_stdio(false);
cin.tie(nullptr);
cpp复制int readInt() {
int x = 0;
char c = getchar();
while (c >= '0' && c <= '9') {
x = x * 10 + (c - '0');
c = getchar();
}
return x;
}
完整测试应包含以下典型用例:
| 输入 | 预期输出 | 测试目的 |
|---|---|---|
| 00:00:00 | 0 | 最小边界 |
| 00:00:01 | 1 | 最小非零值 |
| 01:00:00 | 3600 | 整点小时 |
| 00:01:00 | 60 | 整点分钟 |
| 00:00:59 | 59 | 最大秒数 |
| 23:59:59 | 86399 | 最大边界 |
| 12:34:56 | 45296 | 随机常规值 |
cpp复制int total = 45296;
int h = total / 3600;
int m = (total % 3600) / 60;
int s = total % 60;
cpp复制int diff = (h2 - h1) * 3600 + (m2 - m1) * 60 + (s2 - s1);
if (diff < 0) diff += 24 * 3600; // 处理跨天
Python示例(对比理解):
python复制h, m, s = map(int, input().split(':'))
print(h * 3600 + m * 60 + s)
Java示例:
java复制import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] time = sc.next().split(":");
int h = Integer.parseInt(time[0]);
int m = Integer.parseInt(time[1]);
int s = Integer.parseInt(time[2]);
System.out.println(h * 3600 + m * 60 + s);
}
}
cpp复制void fastIO() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
cpp复制assert(h >= 0 && h < 24);
assert(m >= 0 && m < 60);
assert(s >= 0 && s < 60);
在实际竞赛中遇到此类题目,建议采取以下步骤: