Problem Description
输入N个员工,每个员工输出ID号,上班时间,下班时间,第一行输出最早去的员工的ID和上班时间,第二行输出最迟走的员工的ID和下班时间,第三行输出工作最久的员工的ID和上班时间。
Input
第一行输入N表示有N个员工,在接下来的N行,依次输入员工ID,上班打卡时间,下班打卡时间。
Output
在接下来的三行依次输出最早来的员工ID,上班时间。最迟走的员工ID,下班时间。工作时间最久的员工ID和上班时长。
Sample Input
3
ID100001 07:00:00 17:00:00
ID100002 08:00:00 18:00:00
ID100003 09:00:00 21:00:00
Sample Output
ID100001 07:00:00
ID100003 21:00:00
ID100003 12:00:00
解题思路
- 利用结构体录入员工信息和时间信息。
- 将时分秒统一转化为秒,方便比较。
经验总结
- 字符和数字一起录入时,需用getchar()吸收空格,也可将空格直接写入scanf()函数的格式中。
- printf(“%02d”, time.hour)的格式中,2表示占用两位,0表示不足两位补0。
代码实现(C)
#include <stdio.h>
#include <limits.h>
#define MaxSize 10000
// 时分秒对应的秒数
const int convert[3] = {60 * 60, 60, 1};
// 时间结构体
typedef struct Time {
int hour; // 时
int minute; // 分
int second; // 秒
int toSecond; // 对应的秒数
} Time;
typedef struct Staff {
char ID[20]; // 员工id
Time up; // 员工上班时间
Time down; // 员工下班时间
} Staff;
Staff staff[MaxSize];
// 将时间转化为秒数
void timeToSecond(Time *time) {
time->toSecond = time->hour * convert[0] + time->minute * convert[1] + time->second * convert[2];
}
// 将秒数转化为时间
Time secondToTime(int toSecond) {
Time time;
time.toSecond = toSecond;
time.hour = toSecond / convert[0];
time.minute = toSecond % convert[0] / convert[1];
time.second = toSecond % convert[0] % convert[1] / convert[2];
return time;
}
// 打印输出时间
void printTime(Time time) {
printf("%02d:%02d:%02d\n", time.hour, time.minute, time.second);
}
// 打印输出最早来的员工信息
void earliestUp(int N) {
int j = -1, Min = INT_MAX;
for (int i = 0; i < N; ++i) {
if (staff[i].up.toSecond < Min) {
j = i;
Min = staff[i].up.toSecond;
}
}
printf("%s ", staff[j].ID);
printTime(staff[j].up);
}
// 打印输出最晚走的员工信息
void latestDown(int N) {
int j = -1, Max = INT_MIN;
for (int i = 0; i < N; ++i) {
if (staff[i].down.toSecond > Max) {
j = i;
Max = staff[i].down.toSecond;
}
}
printf("%s ", staff[j].ID);
printTime(staff[j].down);
}
// 打印输出工作时间最久的员工信息
void longestLast(int N) {
int j = -1, Max = INT_MIN;
int lastSecond;
for (int i = 0; i < N; ++i) {
lastSecond = staff[i].down.toSecond - staff[i].up.toSecond;
if (lastSecond > Max) {
j = i;
Max = lastSecond;
}
}
Time time = secondToTime(Max);
printf("%s ", staff[j].ID);
printTime(time);
}
int main() {
int N;
while (~scanf("%d", &N)) {
// 录入员工数据
for (int i = 0; i < N; ++i) {
scanf("%s", staff[i].ID);
getchar(); // 吸收空格
scanf("%d:%d:%d", &staff[i].up.hour, &staff[i].up.minute, &staff[i].up.second);
timeToSecond(&staff[i].up); // 将上班时间转化为秒
getchar(); // 吸收空格
scanf("%d:%d:%d", &staff[i].down.hour, &staff[i].down.minute, &staff[i].down.second);
timeToSecond(&staff[i].down); // 将下班时间转化为秒
}
earliestUp(N); // 打印输出最早来的员工信息
latestDown(N); // 打印输出最晚走的员工信息
longestLast(N); // 打印输出工作时间最久的员工信息
}
return 0;
}